文章目录
简介
RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程HTTP服务的方法,能够大大提高客户端的编写效率。
Spring项目配置
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
添加配置交由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);
}
}
快速使用
GET请求
无参无请求头的方式
//GET请求
//无参无请求头的方式
RestTemplate restTemplate=new RestTemplate();
String url1="http://127.0.0.1:9999/test/restTemplateTest";
JSONObject jsonObject=restTemplate.getForObject(url1, JSONObject.class);
log.info("GET请求方式,无参无请求头的方式,得到的结果为:{}",jsonObject.toString());
String url2="http://127.0.0.1:9999/test/restTemplateTest";
ResponseEntity<JSONObject> jsonObject1=restTemplate.getForEntity(url1, JSONObject.class);
无参并指定请求头的方式
paraMap为空
//无参并指定请求头的方式 paramMap是空
Map<String,Object> paramMap = new HashMap<String,Object>();
//设置请求头
HttpHeaders headers=new HttpHeaders();
headers.add("auth","12345");
HttpEntity<Object> entity=new HttpEntity<>(paramMap,headers);
ResponseEntity<JSONObject> result = restTemplate.exchange(url1, HttpMethod.GET,entity, JSONObject.class,paramMap);
if(result.getStatusCodeValue()==200){
JSONObject body=result.getBody();
}
有参的方式
//有参数的方式
Map<String,String> paramMap1=new HashMap<>();
paramMap1.put("userId","123456");
ResponseEntity<JSONObject> result1=restTemplate.getForEntity(url1+"?userId={userId}", JSONObject.class,paramMap1);
if(result1.getStatusCodeValue()==200){
JSONObject body=result1.getBody();
}
有参数并指定请求头
//有参数并指定请求头
Map<String,Object> paramMap2=new HashMap<>();
paramMap2.put("userId","123456");
//设置请求头
HttpHeaders headers1=new HttpHeaders();
headers1.add("auth","123456");
HttpEntity<Object> entity2=new HttpEntity<>(paramMap2,headers1);
ResponseEntity<JSONObject> result3=restTemplate.exchange(url1+"?userId={userId}",HttpMethod.GET,entity,JSONObject.class,paramMap2);
优雅地拼接参数
我们可以发现带参数的get请求,如果采用拼接的方式在参数比较少的时候是适用的,但是参数多了的话就比较麻烦。
下面我们通过UriComponentsBuilder来解决
MultiValueMap<String,String> param=new LinkedMultiValueMap<>();
paramMap.add("userId","123456");
UriComponentsBuilder builder=UriComponents.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();
}
优雅的拼接参数并携带请求头
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();
}
}
getForObject.getForEntity和exchange的区别
- getForObject返回值直接是响应体内容转换为指定的对象;
- getForEntity返回值的封装包含有响应头,响应状态码的ResponseEntity对象;
- exchange可以指定为get请求或者post请求,并且返回ResponseEntity对象。
POST请求
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","123456789");
HttpEntity<Object> entity=new HttpEntity<Object>(paramMap,heanders);
JSONObject result=restTemplate.postForObject(url,entity,JSONObject.class);
表单的方式
MultiValueMap<String,String> paramMap = new LinkedMuiltiValueMap<>();
paramMap.put("userId","123456");
//设置请求头
HttpHeaders headers=new HttpHeaders();
headers.add("Content-Type","application/x-www-form-urlencode");
headers.add("auth","123456");
HttpEntity<Object> entity=new HttpEntity<Object>(paramMap,headers);
JSONObject result=restTemplate.postForObject(url,entity,JSONObject.class);
注意:
使用RestTemplate提交表单时必须使用MultiValueMap来传参
是因为用HashMap定义的参数在使用表单方式传递的时候,最终数据是以json形式传过去的。