如何忽略 Apache HttpComponents HttpClient 5.1 中的 SSL 证书错误

How to ignore SSL certificate errors in Apache HttpComponents HttpClient 5.1

如何使用 Apache HttpComponents HttpClient 5.1 绕过证书验证错误?

我发现 working solution 可以绕过 HttpClient 4.5 中的此类错误,建议自定义 HttpClient 实例:

HttpClient httpClient = HttpClients
            .custom()
            .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, TrustAllStrategy.INSTANCE).build())
            .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
            .build();

但它不适用于 HttpClient 5.1,因为 setSSLContextsetSSLHostnameVerifier 方法在 HttpClientBuilder 中不存在(HttpClients.custom() returns)。

HC 5.1 中有几个专门的构建器可用于执行相同的操作:

CloseableHttpClient httpclient = HttpClients.custom()
        .setConnectionManager(PoolingHttpClientConnectionManagerBuilder.create()
                .setSSLSocketFactory(SSLConnectionSocketFactoryBuilder.create()
                        .setSslContext(SSLContextBuilder.create()
                                .loadTrustMaterial(TrustAllStrategy.INSTANCE)
                                .build())
                        .setHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                        .build())
                .build())
        .build();