忽略 Apache HttpClient 4.3 中的 SSL 证书

2022-08-31 09:40:43

如何忽略 Apache HttpClient 4.3 的 SSL 证书(全部信任)?

我在SO上找到的所有答案都处理以前的版本,并且API发生了变化。

相关:

编辑:

  • 它仅用于测试目的。孩子们,不要在家里(或生产中)尝试

答案 1

下面的代码适用于信任自签名证书。在创建客户端时,您必须使用TrustSelfSignedStrategy

SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
        builder.build());
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(
        sslsf).build();

HttpGet httpGet = new HttpGet("https://some-server");
CloseableHttpResponse response = httpclient.execute(httpGet);
try {
    System.out.println(response.getStatusLine());
    HttpEntity entity = response.getEntity();
    EntityUtils.consume(entity);
} finally {
    response.close();
}

我没有故意包括:重点是允许使用自签名证书进行测试,这样您就不必从证书颁发机构获取适当的证书。您可以轻松地创建具有正确主机名的自签名证书,因此请执行此操作,而不是添加标志。SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIERSSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER


答案 2

如果您使用的是 PoolingHttpClientConnectionManager 上述过程不起作用,则将忽略自定义 SSLContext。在创建 PoolingHttpClientConnectionManager 时,您必须在构造函数中传递 socketFactoryRegistry。

SSLContextBuilder builder = SSLContexts.custom();
builder.loadTrustMaterial(null, new TrustStrategy() {
    @Override
    public boolean isTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
        return true;
    }
});
SSLContext sslContext = builder.build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
        sslContext, new X509HostnameVerifier() {
            @Override
            public void verify(String host, SSLSocket ssl)
                    throws IOException {
            }

            @Override
            public void verify(String host, X509Certificate cert)
                    throws SSLException {
            }

            @Override
            public void verify(String host, String[] cns,
                    String[] subjectAlts) throws SSLException {
            }

            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });

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

PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(
        socketFactoryRegistry);
CloseableHttpClient httpclient = HttpClients.custom()
        .setConnectionManager(cm).build();