我使用PoolingHttpClientconnectionManager,我需要在每个请求上使用特定的sslcontext。默认情况下,CloseableHttpClient 使用管理器的 sslcontext,但我需要来自 .setSSLContext(context( 的 sslcontext。如何解决这个问题?我需要连接池,同时我需要每个请求上的特定 sslcontext
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(httpPoolManager.getConnectionManager())
.setSSLSocketFactory(new SSLConnectionSocketFactory(context, NoopHostnameVerifier.INSTANCE))
.setSSLContext(context)
.build();
setExternalRequestId(externalRequestId);
setHttpClient(client);
那些天我正在研究这个问题。
您可以使用以下代码来构建 HTTPs 客户端:
SSLContextBuilder builder = new SSLContextBuilder();
// Truest all request
try {
builder.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
});
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), new String[] {"TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register(HTTPS, sslsf)
.build();
PoolingHttpClientConnectionManager pccm = new PoolingHttpClientConnectionManager(registry);
然后:
HttpClients.custom()
.setSSLSocketFactory(sslsf)
.setConnectionManager(pccm)
.setConnectionManagerShared(true)
.build();
我不得不挖掘源代码,但发现了以下作品,假设您可以构建自己的PoolingHttpClientConnectionManager
。
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", new SSLConnectionSocketFactory(sslContext))
.build();
CloseableHttpClient httpClient = HttpClientBuilder.create()
// important line -- use registry in constructor
.setConnectionManager(new PoolingHttpClientConnectionManager(registry)) // IMPORTANT
.build();