RestTemplate可以自动映射JavaBean,免去了处理数据的过程。
工具类
private RestTemplate restTemplate;
@Autowired
public RestTemplateUtil(RestTemplate restTemplate){
this.restTemplate = restTemplate;
}
public RestTemplateUtil() {
}
/**
* 自定义请求头和请求体的请求调用方式
*
* @param url 请求URL
* @param httpMethod 类型
* @param requestEntity 请求头和请求体封装对象
* @param responseType 返回对象类型
* @param uriVariables URL中的变量,按顺序依次对应
* @return ResponseEntity 响应对象封装类
*/
public <T> ResponseEntity<T> getResponseEntity(String url,HttpMethod httpMethod, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables) {
return restTemplate.exchange(url, httpMethod, requestEntity, responseType, uriVariables);
}
配置类
@Configuration
@ConditionalOnClass(value = {RestTemplate.class, HttpClient.class})
public class RestTemplateConfiguration {
@Value("${remote.maxTotalConnect:10}")
private int maxTotalConnect; //连接池的最大连接数默认为0
@Value("${remote.maxConnectPerRoute:100}")
private int maxConnectPerRoute; //单个主机的最大连接数
@Value("${remote.connectTimeout:2000}")
private int connectTimeout; //连接超时默认2s
@Value("${remote.readTimeout:30000}")
private int readTimeout; //读取超时默认30s
//创建HTTP客户端工厂
private ClientHttpRequestFactory createFactory() {
if (this.maxTotalConnect <= 0) {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(this.connectTimeout);
factory.setReadTimeout(this.readTimeout);
return factory;
}
HttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(this.maxTotalConnect)
.setConnectionTimeToLive(10, TimeUnit.SECONDS).evictIdleConnections(10, TimeUnit.SECONDS)
.setConnectionManagerShared(false).evictIdleConnections(10, TimeUnit.SECONDS)
.setMaxConnPerRoute(this.maxConnectPerRoute).build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(
httpClient);
factory.setConnectTimeout(this.connectTimeout);
factory.setReadTimeout(this.readTimeout);
return factory;
}
//初始化RestTemplate,并加入spring的Bean工厂,由spring统一管理
@Bean
@ConditionalOnMissingBean(RestTemplate.class)
public RestTemplate getRestTemplate() {
RestTemplate restTemplate = new RestTemplate(this.createFactory());
List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();
//重新设置StringHttpMessageConverter字符集为UTF-8,解决中文乱码问题
HttpMessageConverter<?> converterTarget = null;
for (HttpMessageConverter<?> item : converterList) {
if (StringHttpMessageConverter.class == item.getClass()) {
converterTarget = item;
break;
}
}
if (null != converterTarget) {
converterList.remove(converterTarget);
}
converterList.add(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
return restTemplate;
}
}
使用
Model model = restTemplateUtil.getResponseEntity(Url, HttpMethod.GET, Model.class, params).getBody();