忽略 Apache HTTPClient 4.5 中的自签名证书

Ignore self-signed certificates in Apache HTTPClient 4.5

我正在尝试接受所有证书,and/or接受自签名证书 使用 Apache HTTPClient 版本 4.5(教程link here)

我一直在通过 SO 上的一堆帖子来解决这个问题。到目前为止,其中 none 个已经奏效。

我一直收到这个错误:Error while trying to execute request. javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake

Apache 文档:

相关 Whosebug 问题 - 这是我尝试过的一些 link 解决方案:

请注意,在所有这些示例中,我还传递了我之前定义的 cookie 存储和代理凭据提供程序。这些都在工作,我只是想添加 SSL 支持。

尝试#1

使用 SSLContextBuilder 创建我自己的 ssl 上下文,并使用 TrustSelfSignedStrategy 信任所有自签名策略。

SSLContextBuilder sshbuilder = new SSLContextBuilder();
sshbuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sshbuilder.build());

CloseableHttpClient httpclient = HttpClients.custom()
    .setDefaultCredentialsProvider(credsProvider)
    .setDefaultCookieStore(cookieStore)
    .setSSLSocketFactory(sslsf)
    .build();

结果:没有成功。得到 Error while trying to execute request. javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake

尝试 #2

同上,但加了一个PoolingHttpClientConnectionManager

SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(),SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
        .register("http", new PlainConnectionSocketFactory())
        .register("https", sslsf)
        .build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
cm.setMaxTotal(2000);//max connection

CloseableHttpClient httpclient = HttpClients.custom()
    .setDefaultCredentialsProvider(credsProvider)
    .setDefaultCookieStore(cookieStore)
    .setSSLSocketFactory(sslsf)
    .setConnectionManager(cm)
    .build();

结果:没有成功。得到 Error while trying to execute request. javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake

尝试#3

通过覆盖 TrustStrategy 简单地接受所有证书(不推荐这样做)

SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustStrategy() {
    @Override
    public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        return true;
    }
});
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(),
    SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

CloseableHttpClient httpclient = HttpClients.custom()
    .setDefaultCredentialsProvider(credsProvider)
    .setDefaultCookieStore(cookieStore)
    .setSSLSocketFactory(sslsf)
    .build();

结果:没有成功。得到 Error while trying to execute request. javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake

尝试 #4

我从 this answer 中找到了一些有用的东西:

As of version 4.5 HttpClient disables SSLv3 protocol version by default

这是他给出的解决方案:

SSLContext sslcontext = SSLContexts.createSystemDefault();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
        sslcontext, new String[] { "TLSv1", "SSLv3" }, null,
        SSLConnectionSocketFactory.getDefaultHostnameVerifier());

Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
        .register("http", PlainConnectionSocketFactory.INSTANCE)
        .register("https", sslConnectionSocketFactory)
        .build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);

httpclient = HttpClients.custom()
    .setDefaultCredentialsProvider(credsProvider)
    .setDefaultCookieStore(cookieStore)
    .setSSLSocketFactory(sslConnectionSocketFactory)
    .setConnectionManager(cm)
    .build();

结果:没有成功。得到 Error while trying to execute request. javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake

上述方法之一应该适用于自签名证书,但奇怪的是您在所有方法中都遇到相同的异常。

我觉得在 SSL 会话建立期间或握手协议未被客户端或服务器接受。

此处最好的解决方案是调试应用程序。

如果是tomcat,在setenv.sh或setenv.bat文件中添加-Djavax.net.debug=all,然后重启服务器。

或者您可以关注this tutorial.

OP 只需要在连接到 SSL 时更改端口:

//For HTTPS
HttpHost httpstarget = new HttpHost("mysite.com", 443, "https");

//For HTTP
HttpHost httptarget = new HttpHost("mysite.com", 80, "http");

此问题与 SSL 连接有关。当您尝试连接到某些资源时 https protocol 需要创建安全连接。这意味着只有您的浏览器和网站服务器知道请求正文中发送了哪些数据。这种安全性是通过存储在网站上的 ssl 证书实现的,并由您的浏览器(或任何其他客户端,在我们的例子中为 Apache Http 客户端)在首次连接到主机时下载。有 RSA256 加密和许多其他很酷的东西。 但在一天结束时:如果证书未注册或无效,您将看到证书错误(HTTPS 连接不安全)。 要修复证书错误,网站提​​供商需要为特定网站购买它或以某种方式修复,例如https://www.register.com/ssl-certificates

但是当您使用

跳过 ssl 验证时会有绕过
(s, sslSession) -> true

这是安全违规,因为您不能 100% 确定您的数据是安全的,但是当使用测试数据和受信任的网站时,此解决方案可用于测试或配置

public static HttpClient newClient() {
            SSLContext sslcontext = null;
            try {
                sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
            } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
                e.printStackTrace();
            }

            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext,
                    (s, sslSession) -> true);

            return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory)
                    .build();
        }

很多时候,您不仅需要支持自签名证书,还需要调用多线程请求,因此需要使用池连接管理器。以下是我的做法:

private CloseableHttpClient newClient() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    SSLContext context = SSLContexts.custom()
            .loadTrustMaterial(TrustSelfSignedStrategy.INSTANCE)
            .build();

    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(context, NoopHostnameVerifier.INSTANCE))
            .build();

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);

    return HttpClients.custom()
            .setConnectionManager(connectionManager)
            .build();
}

我正在使用 Apache HttpClient 4.5.3,上述解决方案 none 有帮助。我总是收到错误

PKIX Path building failed

.

我在 http://www.baeldung.com/httpclient-ssl

中找到了解决方案

这是我的代码:

try {
    SSLContext sslContext = new SSLContextBuilder()
            .loadTrustMaterial(null, (certificate, authType) -> true).build();
    httpClient = HttpClients.custom().setSSLContext(sslContext)
            .setSSLHostnameVerifier(new NoopHostnameVerifier())
            .build();
} catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
    e.printStackTrace();
}