java - Apache Http 客户端 SSL 证书错误

标签 java ssl https httpclient apache-httpclient-4.x

我知道之前有人问过这个问题,但我尝试了我找到的所有解决方案,但仍然无法正常工作。

基本上,我正在尝试通过 Apache Http 客户端 (4.3) 获取一些内容,但我连接的网站存在一些 SSL 问题。

首先,我收到了 SSLExceptionunrecognized_name 消息。我试图通过将 jsse.enableSNIExtension 属性设置为 false 来解决这个问题。

然后,我得到了这个异常: javax.net.ssl.SSLHandshakeException:sun.security.validator.ValidatorException:PKIX 路径构建失败:sun.security.provider.certpath.SunCertPathBuilderException:无法找到请求目标的有效证书路径

然后,我尝试提供我赢得的 SSLFactory,它将接受所有证书,但我仍然遇到相同的异常。这是我的代码:

private static void sslTest() throws Exception {
    System.setProperty("jsse.enableSNIExtension", "false");

    SSLContext sslContext = SSLContexts.custom()
            .loadTrustMaterial(null, new TrustSelfSignedStrategy())
            .useTLS()
            .build();

    SSLConnectionSocketFactory connectionFactory =
            new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());

    CookieStore cookieStore = new BasicCookieStore();
    HttpClientContext context = HttpClientContext.create();
    context.setCookieStore(cookieStore);

    CloseableHttpClient httpclient = HttpClients.custom()
            .setSSLSocketFactory(connectionFactory)
            .setDefaultCookieStore(cookieStore)
            .build();

    URI uri = new URIBuilder()
            .setScheme("https")
            .setHost(BASE_URL)
            .build();

    String responseBody = httpclient.execute(new HttpGet(uri), RESPONSE_HANDLER);
}

非常感谢所有帮助!

最佳答案

另请注意,信任自签名证书并不意味着信任任何任意证书。

尝试以这种方式设置您的 SSL 上下文:

SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, 
    new TrustStrategy() {
        @Override
        public boolean isTrusted(final X509Certificate[] chain, final String authType) 
        throws CertificateException {
            return true;
        }
    })
    .useTLS()
    .build();

另请注意,通常不加区别地信任证书首先违背了使用 SSL 的目的。在绝对必要或仅用于测试时使用

关于java - Apache Http 客户端 SSL 证书错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24720013/

相关文章:

WCF传输安全弱点

java - 提交同一 jsp 中存在的第二个表单时出错...需要建议

http - 使用 F# 连接时如何接受 SSL 证书?

java - 如何读取由特殊字符分隔的hadoop中的文本源

python - 如何在 python 中验证服务器的 ssl 证书?

authentication - 使用相互 SSL 将 Glassfish 配置为 Web 服务的客户端

.htaccess - 如何使用 htaccess 仅在某些页面上启用 https?

使用具有不同协议(protocol)的代理的 PHP cURL 请求

java - 我可以通过将 ECore 模型导入其他模型来重用它们吗?

java - 如何在 Java 中跟踪线程池中的 Runnables?