Spring restTemplate使用

最近看到spring RestTemplate,觉得挺好用的,就研究总结了一下,第一次写。。。 
RestTemplate可使用http的所有方式进行请求,本文主要说明下get,post的使用,其他的基本类似。

http get 方式

spring RestTemplate中直接使用get方法有两种getForObject和getForEntity

getForObject

每种方式都有3个重载方法

  1. T getForObject(URI url, Class responseType)
  2. T getForObject(String url, Class responseType, MapString< String, ?> urlVariables)
  3. T getForObject(String url, Class responseType, Object… urlVariables) 
    其中url为请求url,可用通配符表示请求参数,responseType为请求返回的对象类,自动封装成对象该对象形式, Map< String, ?> urlVariables表示请求参数,与通配符对应即可, Object… urlVariables为请求的参数数组形式,按顺序一一匹配url中内容,例子如下: 
    User 类,省略get,set方法
public class User {

    private String name;

    private Integer age;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
private RestTemplate restTemplate = new RestTemplate();

    private String name = "xiaoming";

    private Integer age = 18;
  • 1
  • 2
  • 3
  • 4
  • 5

getForObject 
发送方

String url = "http://localhost:8080/getUser?name={name}&age={age}";
        Object[] arr = new Object[]{name, age};
        User u = restTemplate.getForObject(url, User.class, arr);
  • 1
  • 2
  • 3

    String url = "http://localhost:8080/getUser?name={name}&age={age}";
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("age", age);
        User u = restTemplate.getForObject(url, User.class, map);
  • 1
  • 2
  • 3
  • 4
  • 5

接收方

public User get1(@RequestParam String name, @RequestParam Integer age)
  • 1

getForEntity

getForEntity与getForObject请求参数基本一样,只是返回内容不一样 
ResponseEntity getForEntity(String url, Class responseType, Object… urlVariables) 
getForEntity返回ResponseEntity,里面包含返回消息内容和http headers,http 状态码,如下例

String url = "http://localhost:8080/getUser?name={name}&age={age}";
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("age", age);
        ResponseEntity<User> res = restTemplate.getForEntity(url, User.class, map);
        User u = res.getBody();
        HttpHeaders headers = res.getHeaders();
        HttpStatus status = res.getStatusCode();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

以上是RestTemplate的get请求使用方式,对于get请求传送head信息的,实现在下面说到

http post 方式

post方法主要有3种方法:postForObject, postForEntity和postForLocation

postForObject

同样有3种重载

  1. T postForObject(String url, Object request, Class responseType, Object… uriVariables)
  2. T postForObject(String url, Object request, Class responseType, Map
private HttpEntityRequestCallback(Object requestBody, Type responseType) {
            super(responseType);
            if (requestBody instanceof HttpEntity) {
                this.requestEntity = (HttpEntity<?>) requestBody;
            }
            else if (requestBody != null) {
                this.requestEntity = new HttpEntity<Object>(requestBody);
            }
            else {
                this.requestEntity = HttpEntity.EMPTY;
            }
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

可以看到Object request最终都会转换为HttpEntity,httpEntity类中如下

public class HttpEntity<T> {

    /**
     * The empty {@code HttpEntity}, with no body or headers.
     */
    public static final HttpEntity<?> EMPTY = new HttpEntity<Object>();


    private final HttpHeaders headers;

    private final T body;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

主要包含headers和body两部分内容,如果Object request可直接转为HttpEntity,则可直接使用,否则默认为HttpEntity中body的内容 
参数传递,这种post方式可以避开get方法参数过长的影响,不限制参数长度

String url = "http://localhost:8080/getUser";
        LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("name", name);
        map.add("age", age);

        User u = restTemplate.postForObject(url, map, User.class);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

String url = "http://localhost:8080/getUser";
        LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("name", name);
        map.add("age", age);

        HttpEntity<LinkedMultiValueMap<String, Object>> httpEntity = new HttpEntity<>(map);

        User u = restTemplate.postForObject(url, httpEntity, User.class);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

接收方

 public User get1(@ModelAttribute User user)
  • 1

传递http head信息,可自行设置http请求的head信息 
发送方

String url = "http://localhost:8080/getUser";
        LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("name", name);
        map.add("age", age);

        HttpHeaders headers = new HttpHeaders();
        headers.add("msg", "head msg test");    

        HttpEntity<LinkedMultiValueMap<String, Object>> httpEntity = new HttpEntity<>(map, headers);

        User u = restTemplate.postForObject(url, httpEntity, User.class);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

接收方

@RequestMapping(value = "/getUser", method = {RequestMethod.POST})
    public User get1(@RequestParam String name, @RequestParam Integer age, @RequestHeader(required = false)  String msg)
  • 1
  • 2

postForEntity和postForLocation

postForEntity返回ResponseEntity,与getForEntity相同 
postForLocation返回URI,返回的是response header中的location信息,一般用于资源定位。

exchange方法

spring直接提供了所有http的请求的公用方法exchange,简单介绍下

ResponseEntity exchange(String url, HttpMethod method, 
HttpEntity< ?> requestEntity, Class responseType, Object… uriVariables) 
参数设置基本相同,多了个HttpMethod ,设置http的请求方式,通过这个就可以设置Http Get方式的头信息

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring RestTemplateSpring框架中的一个重要组件,用于简化HTTP请求的发送。使用RestTemplate可以实现对RESTful Web服务的访问,支持GET、POST、PUT、DELETE等常见的HTTP请求方法。 下面是Spring RestTemplate的一些基本使用方法: 1. 创建RestTemplate实例: ```java RestTemplate restTemplate = new RestTemplate(); ``` 2. 发送GET请求: ```java String url = "http://example.com/users/{userId}"; ResponseEntity<User> response = restTemplate.getForEntity(url, User.class, userId); ``` 3. 发送POST请求: ```java String url = "http://example.com/users"; User user = new User(); ResponseEntity<User> response = restTemplate.postForEntity(url, user, User.class); ``` 4. 发送PUT请求: ```java String url = "http://example.com/users/{userId}"; User user = new User(); restTemplate.put(url, user, userId); ``` 5. 发送DELETE请求: ```java String url = "http://example.com/users/{userId}"; restTemplate.delete(url, userId); ``` RestTemplate还有很多其他的方法,更详细的使用方法可以参考Spring官方文档。 ### 回答2: Spring RestTemplateSpring框架提供的用于处理RESTful请求的模板类。它封装了底层的HTTP通信细节,提供了简化的API,使得开发者可以更方便地发送HTTP请求和接收响应。 在使用RestTemplate之前,我们首先需要在项目的依赖中引入Spring的web模块,因为RestTemplate是web模块的一部分。 使用RestTemplate发送HTTP请求的步骤如下: 1. 创建一个RestTemplate对象。可以直接通过new关键字创建,也可以通过Spring的依赖注入方式获取。 2. 选择合适的请求方法,并设置请求的URL和请求参数。RestTemplate提供了多种请求方法,如GET、POST等。我们可以通过参数的形式传递URL,并可以使用Map或对象封装请求参数。 3. 发送请求,并接收响应。可以调用RestTemplate的exchange()方法来发送请求,并通过ResponseEntity来接收响应。exchange方法可以指定请求方法、URL、请求体、请求头等信息,并可以通过参数化类型来指定响应的类型。 4. 解析响应。根据实际需要,我们可以使用ResponseEntity的getBody()方法获取响应的主体内容,并进行进一步的解析。 需要注意的是,使用RestTemplate发送请求时,我们可以自己编写请求头、请求体等信息,也可以通过使用RestTemplate提供的辅助方法来简化请求的构建。此外,RestTemplate还提供了异常处理和重试机制,可以更好地处理异常情况。 总的来说,Spring RestTemplate提供了简洁易用的API,帮助我们快速发送HTTP请求和处理响应,节省了开发时间和精力。它是Spring框架中非常重要的一部分,值得开发者深入学习和掌握。 ### 回答3: Spring RestTemplateSpring框架中的一个HTTP访问客户端工具,它可以方便地进行HTTP请求的发送和响应的处理。 在使用RestTemplate之前,首先需要引入相关的依赖。在Maven项目中,可以通过在pom.xml文件中添加以下依赖来使用RestTemplate: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 引入依赖后,可以通过如下方式创建一个RestTemplate对象: ``` RestTemplate restTemplate = new RestTemplate(); ``` 之后就可以使用RestTemplate对象来发送HTTP请求了。RestTemplate提供了多种发送请求的方法,例如getForObject()、postForObject()等。 使用getForObject()方法发送GET请求并接收响应: ``` String url = "http://api.example.com/data"; String response = restTemplate.getForObject(url, String.class); ``` 使用postForObject()方法发送POST请求并接收响应: ``` String url = "http://api.example.com/data"; String requestBody = "param1=value1&param2=value2"; String response = restTemplate.postForObject(url, requestBody, String.class); ``` RestTemplate还提供了其他一些方法,例如exchange()方法可以发送更复杂的请求,并接收带有响应头和状态码等信息的响应对象。 在使用RestTemplate发送请求时,可以通过设置请求头、请求体、URI参数等来定制请求。可以通过如下方式来设置请求头: ``` HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", "Bearer token"); HttpEntity<String> requestEntity = new HttpEntity<>(headers); ``` 可以通过如下方式来设置请求体: ``` MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>(); requestBody.add("param1", "value1"); requestBody.add("param2", "value2"); HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(requestBody); ``` 可以通过如下方式来设置URI参数: ``` String url = "http://api.example.com/data?param1={param1}&param2={param2}"; Map<String, String> uriVariables = new HashMap<>(); uriVariables.put("param1", "value1"); uriVariables.put("param2", "value2"); String response = restTemplate.getForObject(url, String.class, uriVariables); ``` 总结来说,Spring RestTemplate是一个用于发送和处理HTTP请求的方便工具,通过引入相关依赖并创建RestTemplate对象,可以使用它发送不同类型的HTTP请求,并对响应进行处理。通过设置请求头、请求体、URI参数等,可以对请求进行定制。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值