托马斯,也许为时已晚,但我希望它能帮助别人……
有一个方法,我用它来使用Apache HttpClient 4.3创建CloseableHttpClient:
public static CloseableHttpClient prepareClient() {
try {
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS().build();
HttpClientBuilder builder = HttpClientBuilder.create();
SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
builder.setSSLSocketFactory(sslConnectionFactory);
Registry registry = RegistryBuilder.create()
.register("https", sslConnectionFactory)
.register("http", new PlainConnectionSocketFactory())
.build();
HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);
builder.setConnectionManager(ccm);
return builder.build();
} catch (Exception ex) {
return null;
}
}
Apache Foundation移动org.apache.http.conn.ssl.SSLContextBuilder,org.apache.http.conn.ssl.SSLContexts和org.apache.http.conn.ssl.SSLSocketFactory从4.4版本开始不推荐使用,There你可以找到Apache客户端4.5.2 API已删除列表.因此,可以像这样改变以前的方法:
public static CloseableHttpClient prepareClient() {
try {
SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
HttpClientBuilder builder = HttpClientBuilder.create();
SSLConnectionSocketFactory sslConnectionFactory =
new SSLConnectionSocketFactory(sslContext.getSocketFactory(),
new NoopHostnameVerifier());
builder.setSSLSocketFactory(sslConnectionFactory);
Registry registry =
RegistryBuilder.create()
.register("https", sslConnectionFactory)
.register("http", new PlainConnectionSocketFactory())
.build();
HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);
builder.setConnectionManager(ccm);
return builder.build();
} catch (Exception ex) {
LOG.error("couldn't create httpClient!! {}", ex.getMessage(), ex);
return null;
}
}
The NO_OP HostnameVerifier essentially turns hostname verification
off. This implementation is a no-op, and never throws the
SSLException.
如果需要验证主机名,可以使用DefaultHostnameVerifier,也可以实现自定义主机名验证程序.