有了RestTemplate你还在手撕HttpClient?

966 阅读2分钟

原创:花括号MC(微信公众号:huakuohao-mc),欢迎分享,转载请保留出处。

在微服务大行其道的今天,HTTP调用是程序员无法避免的常规操作。

RestTemplateSpring提供的一个,用于发起HTTP调用的客户端。相比于传统的HttpComponentsRestTemplate使用起来更简单,更方便。

发起Get请求
  1. 获取JSON类型的返回
RestTemplate restTemplate = new RestTemplate();
String fooResourceUrl = "http://localhost:8080/spring-rest/foos";
ResponseEntity<String> response = restTemplate.getForEntity(fooResourceUrl + "/1", String.class);
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
  1. 获取POJO类型的返回 我们定义一个Foo
public class Foo implements Serializable {
    private long id;
    private String name; 
    // standard getters and setters 
 }

使用RestTemplate发起Get请求

Foo foo = restTemplate .getForObject(fooResourceUrl + "/1", Foo.class); 
assertThat(foo.getName(), notNullValue()); assertThat(foo.getId(), is(1L));
获取Header信息
HttpHeaders httpHeaders = restTemplate.headForHeaders(fooResourceUrl); 
//获取ContentType
assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON));
发起Post请求
RestTemplate restTemplate = new RestTemplate(); HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));
Foo foo = restTemplate.postForObject(fooResourceUrl, request, Foo.class);
assertThat(foo, notNullValue());
assertThat(foo.getName(), is("bar"));
模拟Form表单提交

通过POST方式提交表单数据,首先需要设置头部信息,将Content-Type 设置为 application/x-www-form-urlencoded

接下来我们将表单中的数据项封装进Map。最后将Header和表单数据一起封装成HttpEntity

代码示例如下

HttpHeaders headers = new HttpHeaders(); 
//设置头部信息
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//将表单信息封装进Map
MultiValueMap<String, String> map= new LinkedMultiValueMap<>(); 
map.add("id", "1");

//将表单数据封装进HttpEntity
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

//发起POST请求
ResponseEntity<String> response = restTemplate.postForEntity( fooResourceUrl+"/form", request , String.class);

assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
通过PUT方式更新资源

更新资源既可以通过PUT方法,也可以通过exchange()。示例如下。

Foo updatedInstance = new Foo("newName"); 

updatedInstance.setId(createResponse.getBody().getId()); 

String resourceUrl = fooResourceUrl + '/' + createResponse.getBody().getId();
HttpEntity<Foo> requestUpdate = new HttpEntity<>(updatedInstance, headers); 
//通过exchange发送PUT类型请求
template.exchange(resourceUrl, HttpMethod.PUT, requestUpdate, Void.class);

//直接通过putAPI进行更新
template.put(resourceUrl,requestUpdate,Void.class);
发起DELETE请求

通过delete删除资源。

String entityUrl = fooResourceUrl + "/" + existingResource.getId();
restTemplate.delete(entityUrl);
通过exchange()发起请求

通过exchange()方法可以发起任意类型的HTTP请求。代码示例如下。

RestTemplate restTemplate = new RestTemplate();
HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar")); 
//传递参数为HttpMethod.POST, 发起POST类型参数
ResponseEntity<Foo> response = restTemplate .exchange(fooResourceUrl, HttpMethod.POST, request, Foo.class);
assertThat(response.getStatusCode(), is(HttpStatus.CREATED));
Foo foo = response.getBody();
assertThat(foo, notNullValue());
assertThat(foo.getName(), is("bar"));
配置超时时间

可以通过ClientHttpRequestFactory配置RestTemplate的超时时间。代码示例如下:

RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory()); 

private ClientHttpRequestFactory getClientHttpRequestFactory() {
    int timeout = 5000;
    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(); 

    clientHttpRequestFactory.setConnectTimeout(timeout);
    return clientHttpRequestFactory;
}
总结

RestTemplate使用起来即简单又方便,RestTemplate的设计思想和JDBCTemplate如出一辙。相信这也是Spring的哲学。

注意:现在RestTemplate已经不被官方推荐使用,官方推荐使用WebClient。下一篇文章将会介绍WebClient的使用。

本文内容主要翻译自 www.baeldung.com/rest-templa…

推荐阅读

1. Java并发编程那些事儿(十)——最后的总结

2. 程序员应该掌握的常用网络问题定位工具

3. Awk这件上古神兵你会用了吗

4. 手把手教你搭建一套ELK日志搜索运维平台

原创:花括号MC(微信公众号:huakuohao-mc)。关注JAVA基础编程及大数据,注重经验分享及个人成长。