RestTemplate最佳实践
2021-11-17 本文已影响0人
liaijuyyer
一 介绍
RestTemplate 是Spring提供的一个用于http访问的工具模板
二 依赖
使用restTemplate需要导入如下pom依赖
<!--restTemplate启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<!--根据需要导入httpcomponents-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.10</version>
</dependency>
三 restTemplate配置
在使用restTemplate之前 还需要简单的对restTemplate进行配置 配置类如下
@Data
@Configuration
@ConfigurationProperties(prefix = "xx.xx.xx")
public class RestTemplateConfig {
private Long connectionTimeout = 1000L;
private Long readTimeout = 1000L;
@Bean //将RestTemplate装配为bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder
.requestFactory(HttpComponentsClientHttpRequestFactory.class)
.setConnectTimeout(Duration.ofMillis(connectionTimeout)) //设置http的链接超时时间
.setReadTimeout(Duration.ofMillis(readTimeout)) //设置http的响应超时时间
.build();
}
}
四 使用restTemplate
@RestController
public class TestController {
@Autowired
private RestTemplate restTemplate;
/**
* 获取nacos中指定dataId的配置信息
**/
@RequestMapping(path = "/getConfig", method = RequestMethod.GET)
public String getConfig(HttpServletRequest request) {
//获取nacos的accessToken
String accessToken = getAccessToken();
accessToken = String.valueOf(JSON.parseObject(accessToken, Map.class).get("accessToken"));
String url = "http://xxxx/nacos/v1/cs/configs?dataId={dataId}&group={group}&tenant={tenant}&accessToken={accessToken}&namespaceId={namespaceId}";
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("dataId","xxx");
paramMap.put("group","DEFAULT_GROUP");
paramMap.put("tenant","xx");
paramMap.put("accessToken", accessToken);
paramMap.put("namespaceId","xxx");
//设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(null, headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class, paramMap);
return response.getBody();
}
/**
* 获取nacos的accessToken
**/
private String getAccessToken() {
String url = "http://xxx/nacos/v1/auth/login";
MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
paramMap.add("username","nacos");
paramMap.add("password","nacos");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); //请求类型为表单
HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(paramMap, headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
return response.getBody();
}
}
五 发送POST请求
使用RestTemplate post请求的时候主要可以通过三种方式实现
- 调用postForObject方法
- 调用postEntity方法
- 调用exchange方法
postForObject和postForEntity方法的区别主要在于可以在postForEntity方法中设置header的属性,当需要指定header的属性值的时候,使用postForEntity方法。exchange方法和postForEntity类似,但是更灵活,exchange还可以调用get、put、delete请求。
ContentType是表单
当ContentType的类型为表单类型时(content-type=application/x-www-form-urlencoded等)post请求的body不能是json也不能是map必须是MultiValueMap类型
private String getAccessToken() {
String url = "http://xxx/nacos/v1/auth/login";
//因为ContentType是表单 所以用MultiValueMap去对表单进行设值
MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
paramMap.add("username","nacos");
paramMap.add("password","nacos");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); //请求类型为表单
HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(paramMap, headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
return response.getBody();
}
ContentType是JSON
当ContentType是json的时候 就没有这么麻烦了 可以直接填充json格式的参数作为bo
@RequestMapping(path = "/test", method = RequestMethod.GET)
public String test() {
String url = "https://xxx/web/message/view/unread";
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("coupon", true);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON); //设值contentType是application/json
headers.add("Cookie", "xxx"); //添加cookie
HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(paramMap), headers); //这里body被转换成了json
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
return response.getBody();
}
六 发送GET请求
restTemplate发送GET请求如果需要带参数 必须在url上填充占位符 示例如下
/**
* 获取nacos中指定dataId的配置信息
**/
@RequestMapping(path = "/getConfig", method = RequestMethod.GET)
public String getConfig(HttpServletRequest request) {
//获取nacos的accessToken
String accessToken = getAccessToken();
accessToken = String.valueOf(JSON.parseObject(accessToken, Map.class).get("accessToken"));
String url = "http://xxxx/nacos/v1/cs/configs?dataId={dataId}&group={group}&tenant={tenant}&accessToken={accessToken}&namespaceId={namespaceId}"; //注意这里url中的{xx}都是占位符
Map<String, Object> paramMap = new HashMap<String, Object>(); //这里用map而不用MultiValueMap
paramMap.put("dataId","xxx");
paramMap.put("group","DEFAULT_GROUP");
paramMap.put("tenant","xx");
paramMap.put("accessToken", accessToken);
paramMap.put("namespaceId","xxx");
//设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(null, headers); //注意get请求时 这里填充的是null
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class, paramMap);
return response.getBody();
}