一、概述
RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。
二、配置
1、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2、添加配置交由spring管理
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(30*1000);
requestFactory.setReadTimeout(30*1000);
return new RestTemplate(requestFactory);
}
}
三、快速使用
1、GET请求
1.1、无参无请求头的方式
String url="http://127.0.0.1:9999/test/restTemplateTest";
JSONObject jsonObject = restTemplate.getForObject(url,JSONObject.class);
String url="http://127.0.0.1:9999/test/restTemplateTest";
ResponseEntity<JSONObject> jsonObject = restTemplate.getForEntity(url,JSONObject.class);
1.2、无参并指定请求头的方式
paramMap 是空
Map<String, Object> paramMap = new HashMap<String, Object>();
//设置请求头
HttpHeaders headers = new HttpHeaders();
headers.add("auth","123445");
HttpEntity<Object> entity = new HttpEntity<>(paramMap,headers);
ResponseEntity<JSONObject> result = restTemplate.exchange(url, HttpMethod.GET, entity, JSONObject.class, paramMap);
if (result.getStatusCodeValue() == 200){
JSONObject body = result.getBody();
}
1.3、有参的方式
记得要在url中拼接参数 url + “?userId={userId}”
Map<String, String> paramMap = new HashMap<>();
paramMap.put("userId", "123456");
ResponseEntity<JSONObject> result = restTemplate.getForEntity(url + "?userId={userId}", JSONObject.class, paramMap);
if (result.getStatusCodeValue() == 200){
JSONObject body = result.getBody();
}
1.4、有参并指定请求头
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("userId", "123456");
//设置请求头
HttpHeaders headers = new HttpHeaders();
headers.add("auth","123445");
HttpEntity<Object> entity = new HttpEntity<>(paramMap,headers);
ResponseEntity<JSONObject> result = restTemplate.exchange(url + "?userId={userId}", HttpMethod.GET, entity, JSONObject.class, paramMap);
if (result.getStatusCodeValue() == 200){
JSONObject body = result.getBody();
}
1.5、优雅的拼接参数
我们发现带参数的get请求需要将参数拼接到url中,参数少好说,参数多了就很麻烦
我们使用UriComponentsBuilder来解决
MultiValueMap<String, String> paramMap = new LinkedMultiValueMap<>();
paramMap.add("userId", "123456");
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
URI uri = builder.queryParams(paramMap).build().encode(StandardCharsets.ISO_8859_1).toUri();
ResponseEntity<JSONObject> result = restTemplate.getForEntity(uri, JSONObject.class);
if (result.getStatusCodeValue() == 200){
JSONObject body = result.getBody();
}
1.6、优雅的拼接参数并携带请求头
MultiValueMap<String, String> multiValueMap = TaskCenterDataConvert.taskSearchDTOToMultiValueMap(taskSearchDTO);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(taskCenterListSearchUrl);
URI uri = builder.queryParams(multiValueMap).build().encode(StandardCharsets.ISO_8859_1).toUri();
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization","Bearer " + authorization);
HttpEntity<JSONObject> httpEntity = new HttpEntity<>(null, headers);
ResponseEntity<JSONObject> result = restTemplate.exchange(uri.toString(), HttpMethod.GET, httpEntity, JSONObject.class, multiValueMap);
if (result.getStatusCodeValue() == 200){
JSONObject body = result.getBody();
}
}
1.7、getForObject 、getForEntity和exchange 区别
post请求也是相同的道理
- getForObject 返回值直接是响应体内容转为指定的对象
- getForEntity 返回值的封装包含有响应头, 响应状态码的 ResponseEntity 对象
- exchange 可以指定为get请求或者post请求,并且返回ResponseEntity 对象
2、POST请求
2.1、application/json 的方式
其中参数可以指定为map json 或者bean的形式
Map<String, String> paramMap = new HashMap<>();
paramMap.put("userId", "123456");
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type","application/json");
headers.add("auth","12334455666");
HttpEntity<Object> entity = new HttpEntity<Object>(paramMap,headers);
JSONObject result = restTemplate.postForObject(url, entity,JSONObject.class);
2.1、表单的方式
MultiValueMap<String, String> paramMap = new LinkedMultiValueMap<>();
paramMap.add("userId", "123456");
//设置请求头
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/x-www-form-urlencoded");
headers.add("auth","12334455666");
HttpEntity<Object> entity = new HttpEntity<Object>(paramMap, headers);
JSONObject result = restTemplate.postForObject(url, entity, JSONObject.class);
注意:
使用 RestTemplate 提交表单时必须使用 MultiValueMap来传参
是因为是用HashMap定义的参数在使用表单方式传递的时候,最终数据是以json形式传过去的
MultiValueMap 和 Map的区别:
MultiValueMap 一个 key 可以对应多个 value
Map 一个 key 对应一个 value
文章持续更新,可以关注下方公众号或者微信搜一搜「 最后一支迷迭香 」第一时间阅读,获取更完整的链路资料。