public class HttpClientUtil {
private static Logger LOGGER = LoggerFactory.getLogger(HttpClientUtil.class);
private static PoolingHttpClientConnectionManager cm = null;
private static RequestConfig requestConfig = null;
static {
LayeredConnectionSocketFactory sslsf = null;
SSLConnectionSocketFactory scsf = null;
SSLContext sslContext = null;
try {
// 情形1、正常请求,https需要安装证书
// sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault());
// 情形2、信任所有证书 但是https只允许域名访问,不允许ip访问
// sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
// // 信任所有
// public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// return true;
// }
// }).build();
// sslsf = new SSLConnectionSocketFactory(sslContext);
// 情形3、忽略所有证书,可以ip访问
scsf = new SSLConnectionSocketFactory(
SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
NoopHostnameVerifier.INSTANCE);
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
LOGGER.error("创建SSL连接失败");
}
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", scsf)
.register("http", new PlainConnectionSocketFactory())
.build();
cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
//多线程调用注意配置,根据线程数设定
cm.setMaxTotal(200);
//多线程调用注意配置,根据线程数设定
cm.setDefaultMaxPerRoute(300);
requestConfig = RequestConfig.custom()
//数据传输过程中数据包之间间隔的最大时间
.setSocketTimeout(20000)
//连接建立时间,三次握手完成时间
.setConnectTimeout(20000)
//重点参数
.setExpectContinueEnabled(true)
.setConnectionRequestTimeout(10000)
//重点参数,在请求之前校验链接是否有效
.setStaleConnectionCheckEnabled(true)
.build();
}
public static CloseableHttpClient getHttpClient() {
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(cm)
.build();
return httpClient;
}
public static void closeResponse(CloseableHttpResponse closeableHttpResponse) throws IOException {
EntityUtils.consume(closeableHttpResponse.getEntity());
closeableHttpResponse.close();
}
}
笔记:通过HttpClient实现正常请求、信任所有证书请求、忽略所有证书请求。
于 2022-09-13 14:10:20 首次发布