/**
* https方法调用
* @return
*/
public static CloseableHttpClient getHttpsClient() {
RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create();
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
// 信任任何链接
TrustStrategy anyTrustStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException {
// TODO Auto-generated method stub
return true;
}
};
SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, anyTrustStrategy).build();
// 防止缓存过大导致内存过大,这样设置可能会出现频繁GC,可以屏蔽这一行
sslContext.getClientSessionContext().setSessionCacheSize(1000);
LayeredConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1.2", "TLSv1.1", "SSLv3"}, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
registryBuilder.register("https", sslSF);
} catch (KeyStoreException e) {
throw new RuntimeException(e);
} catch (KeyManagementException e) {
throw new RuntimeException(e);
} catch (Exception e) {
throw new RuntimeException(e);
}
return HttpClientBuilder.create().setConnectionManager(new PoolingHttpClientConnectionManager(registryBuilder.build())).build();// 构建客户端
}
调用方法
public static String getHttpsGet(String url, int connTimeout, int readTimeout) throws IOException {
// 创建Get请求
String body = "";
try {
CloseableHttpClient httpClient = getHttpsClient();
HttpGet httpGet = new HttpGet(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1000*connTimeout).setConnectionRequestTimeout(1000*readTimeout).setSocketTimeout(1000*readTimeout).build();
httpGet.setConfig(requestConfig);
CloseableHttpResponse response = httpClient.execute(httpGet); // 由客户端执行(发送)Get请求
HttpEntity responseEntity = response.getEntity(); // 从响应模型中获取响应实体
body = EntityUtils.toString(responseEntity);
}catch (Exception e){
logger.error("调用异常:url{}",url,e.getMessage());
}
return body;
}