原创:花括号MC(微信公众号:huakuohao-mc)。关注JAVA基础编程及大数据,注重经验分享及个人成长。
在微服务大行其道的今天,HTTP
调用是程序员无法避免的常规操作。
RestTemplate
是Spring
提供的一个,用于发起HTTP
调用的客户端。相比于传统的HttpComponents
,RestTemplate
使用起来更简单,更方便。
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));
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));
HttpHeaders httpHeaders = restTemplate.headForHeaders(fooResourceUrl);
//获取ContentType
assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON));
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"));
通过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
方法,也可以通过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
删除资源。
String entityUrl = fooResourceUrl + "/" + existingResource.getId();
restTemplate.delete(entityUrl);
通过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
的使用。
本文内容主要翻译自 https://www.baeldung.com/rest-template
推荐阅读
·END·