使用下面的getHttpClient()方法代替HttpClients.createDefault()即可。(可以不是static)
private static CloseableHttpClient getHttpClient() {
try {
SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(TrustSelfSignedStrategy.INSTANCE)
.build();
ConnectionSocketFactory plainsf = new PlainConnectionSocketFactory();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", plainsf)
.register("https", sslsf)
.build();
HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);
return HttpClients.custom()
.setConnectionManager(cm)
.build();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
主要是配置了信任自签名的证书和不对域名进行校验。
上面是httpclient4.5的,如果是httpclient 3.x的,可以参考官网http://hc.apache.org/httpclient-3.x/sslguide.html
来源:CSDN
作者:cszsc
链接:https://blog.csdn.net/cszsc/article/details/103872075