RestTemplate

https://docs.spring.io/spring-framework/docs/5.1.9.RELEASE/spring-framework-reference/integration.html#rest-resttemplate

RestTemplate 是 Spring 提供的用于访问Rest服务的客户端库。

如果在Springboot项目中使用,包含start-web即可。

Drawing

上面的方法大致可以分为三组:

  • getForObject->optionsForAllow:这类方法是最常规的 Rest API 方法调用。

  • exchange:接收一个RequestEntity参数,可以自己设置methodURLheadersbody等参数,返回ResponseEntity

  • exectue:通过callback接口,可以对请求和返回做更加全面的定义。

一般情况下,我们使用第一组和第二组方法应对日常开发就足够了。

GET 请求

无参 GET 请求

RestTemplate restTemplate = new RestTemplate();
// 发送一个无参的 GET 请求,将响应体作为字符串返回
ResponseEntity<String> response = restTemplate.getForEntity("https://httpbin.org/get", String.class);
// 判断状态码是否是200
if (response.getStatusCode() == HttpStatus.OK) {
    // 获取响应体
    System.out.println(response.getBody());
    // 获取所有响应头
    System.out.println(response.getHeaders());
    // 获取响应头中的Content-Type
    System.out.println(response.getHeaders().getContentType());
}

还可以通过getForObject方法直接将响应体转换为 Java 对象,但是在这种情况下我们是不能得到状态码、响应头等信息。

User user = resTemplate.getForObject("https://httpbin.org/get?id=1", User.class);

携带参数的 GET 请求

RestTemplate restTemplate = new RestTemplate();
String url = "https://httpbin.org/get?name={name}&age={age}";
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class, "zhangsan", "20");
// User response = restTemplate.getForObject(url, User.class, "zhangsan", 20)
// restTemplate.exchange(url, HttpMethod.GET, null, User.class, "zhangsan", 20);

添加请求头

RestTemplate restTemplate = new RestTemplate();
String url = "https://httpbin.org/get";
HttpHeaders headers = new HttpHeaders();
// 添加自定义请求头
headers.add("customHeader", "customHeaderValue");
// 设置请求头
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> httpEntity = new HttpEntity<>(headers);
ResponseEntity<Foo> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, Foo.class);

POST 请求

  1. 调用postForObject()方法。

  2. 使用postForEntity()方法。

  3. 调用exchange()方法。

postForObjectpostForEntity方法的区别主要在于postForEntity方法中设置header属性,

发送json数据

Map<String, String> map = Map.of("key1", "value1", "key2", "value2");
HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(map);
ResponseEntity<String> response = restTemplate.postForEntity("https://httpbin.org/post", httpEntity, String.class);
restTemplate.postForObject("https://httpbin.org/post", httpEntity, String.class);
restTemplate.exchange("https://httpbin.org/post", HttpMethod.POST, httpEntity, String.class);

提交表单

 RestTemplate restTemplate = new RestTemplate();
 // 首先,我们需要将 Content-Type 表头设置为 application/x-www-form-urlencoded
 HttpHeaders headers = new HttpHeaders();
 headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
 // 接下来,我们将表单变量包装到HttpEntity对象中,并将其传递给RestTemplate.exchange()方法。
 MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
 map.add("key1", "value1");
 // 接下来,我们使用HttpEntity实例构建请求
 HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
 // 最后,我们通过在Endpoint上调用restTemplate.postForEntity()方法来执行请求
 ResponseEntity<String> response = restTemplate.postForEntity("http://httpbin.org/post", request, String.class);java

配置超时时间

// 我么可以简单地使用ClientHttpRequestFactory接口的实现来配置超时
private ClientHttpRequestFactory getClientHttpRequestFactory() {
    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
    clientHttpRequestFactory.setConnectTimeout(5000);
    return clientHttpRequestFactory;
}
@Bean
public RestTemplate restTemplate() {
    return new RestTemplate(getClientHttpRequestFactory());
}

最后更新于

这有帮助吗?