无法找到所请求目标的有效证书路径 - java

时间:2015-05-06 13:22:21

标签: java httpclient sslhandshakeexception

我正在尝试使用http://www.ozkary.com/2015/04/entity-framework-associated-table.html对象连接到网站。它适用于我们通常使用的网站(如谷歌)。但是有一个网站,当我尝试连接时,我的程序会出现这个错误..

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1917)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:301)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:295)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1369)
....................
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
at sun.security.validator.Validator.validate(Validator.java:260)
...............

Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:145)
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:131)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
... 27 more

当我尝试从浏览器转到此网址时,我必须点击仍然继续。否则浏览器将无法加载页面。它会出现隐私错误,说您的连接不是隐私

如何在我的java应用程序中克服这个问题..?我希望我的软件能够连接到该网址而不会出现任何错误或者没有要求任何确认。

2 个答案:

答案 0 :(得分:13)

当我使用TrustSelfSignedStrategy对象作为HttpClient的信任材料时问题得以解决。

        httpClient = HttpClients.custom()
            .setSSLSocketFactory(new SSLConnectionSocketFactory(SSLContexts.custom()
                    .loadTrustMaterial(null, new TrustSelfSignedStrategy())
                    .build()
                )
            ).build();

我使用的代码如上所示..

答案 1 :(得分:8)

对于HttpClient4.x,以下内容将信任所有

public static HttpClientBuilder createTrustAllHttpClientBuilder() {
  SSLContextBuilder builder = new SSLContextBuilder();
  builder.loadTrustMaterial(null, (chain, authType) -> true);           
  SSLConnectionSocketFactory sslsf = new 
  SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);
  return HttpClients.custom().setSSLSocketFactory(sslsf);
}