PoolingHttpClientConnectionManager:如何做Https请求?

时间:2013-12-11 05:12:06

标签: java ssl apache-httpcomponents truststore

我目前正在尝试使用HttpGet同时执行多个CloseableHttpClient请求 我搜索了如何做到这一点,答案是使用PoolingHttpClientConnectionManager

此时我得到了这个:

PoolingHttpClientConnectionManager cManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient httpClient = HttpClients.custom()
    .setConnectionManager(cManager)
    .build();

然后我向HttpGet尝试了http://www.google.com请求,一切正常。

然后我通过cmd创建了一个信任库并导入了目标网站的证书,使用我的信任库设置了SSLConnectionSocketFactory并设置SSLSocketFactory httpClient

KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream inputStream = new FileInputStream(new File("myTrustStore.truststore"));
trustStore.load(inputStream, "nopassword".toCharArray());
inputStream.close();

SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
    SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

PoolingHttpClientConnectionManager cManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient httpClient = HttpClients.custom()
    .setSSLSocketFactory(sslsf)
    .setConnectionManager(cManager)
    .build();

如果我尝试执行Https HttpGet,那么我会收到PKIX path building failed例外 如果我在没有.setConnectionManager(cManager)的情况下做同样的事情,一切正常。

你们中的任何人都可以告诉我如何让它发挥作用吗? (别担心,我不创建任何ddos工具)

提前致谢!

P.S。:我正在使用HttpComponents 4.3.1

1 个答案:

答案 0 :(得分:20)

找到答案: https://stackoverflow.com/a/19950935/1223253

只需添加

Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create().register("https", sslsf).build();

并将socketFactoryRegistry作为参数传递给PoolingHttpClientConnectionManager的构造函数。 现在它工作正常:))