Maven 依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
封装方法
public RestTemplate restTemplateHttps() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(scsf)
.build();
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
requestFactory.setReadTimeout(120000);
requestFactory.setConnectTimeout(120000);
requestFactory.setConnectionRequestTimeout(120000);
return new RestTemplate(requestFactory);
}
测试方法
@Test
public void TestGetDataStatus() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
JSONObject callReq = new JSONObject();
callReq.put("aaa","bbb");
RestTemplate restTemplate = restTemplateHttps();
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.valueOf(MediaType.APPLICATION_JSON_VALUE));
HttpEntity<String> httpEntity = new HttpEntity<String>(callReq.toJSONString(), requestHeaders);
ResponseEntity<String> respEntity = restTemplate.exchange("https://aa.com", HttpMethod.POST,httpEntity,
String.class);
}