我知道之前有人问过这个问题,但我尝试了我找到的所有解决方案,但仍然无法正常工作。
基本上,我正在尝试通过 Apache Http 客户端 (4.3) 获取一些内容,但我连接的网站存在一些 SSL 问题。
首先,我收到了 SSLException
和 unrecognized_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/