RestTemplate调用https接口的配置
/**
* restTemplate httpclient 访问https接口
*/
@Bean
public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
//解决中文乱码的问题
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
return restTemplate;
}
这里使用的RestTemplate使用 httpClient
如果要整合其他工具 如 okHttp 可以看RestTemplate的构造函数
public RestTemplate(ClientHttpRequestFactory requestFactory) {
this();
setRequestFactory(requestFactory);
}
需要传入一个ClientHttpRequestFactory 再看ClientHttpRequestFactory有下面的子类
RestTemplate中文乱码的问题
@Bean(name = "httpRestTemplate")
public RestTemplate restTemplateHttp(){
RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
//解决中文乱码的问题
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
return restTemplate;
}
在RestTemplate中传入字符串转换器并指定编码格式
RestTemplate 使用
//参数entity,封装参数
ParamEntity paramEntity = new ParamEntity(new JSONObject(),map);
//指定请求头
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("Content-Type","application/json");
//把参数,跟请求头 组合成 http entity
HttpEntity<ParamEntity> entity = new HttpEntity<>(paramEntity,httpHeaders);
//执行请求 可以指定请求方法 返回
ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST,entity,String.class);
//getBody获取响应体
log.info(responseEntity.getBody());
RestTemplate响应接收文件流 转换
RespnoseEntity<Resource> responseEntity = restTemplate.exchange(url,menthod,entity,Resource.class);
//获取读取流,就可以执行IO 操作
InpuStream in = responseEntity.getBody().getInpuStream();