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

2022-09-03 09:28:39

我正在尝试使用 HttpClient 对象连接到网站。它适用于我们通常使用的网站(如谷歌)。但是有一个网站,当我尝试连接时,我的程序给出了这个错误。

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

当我尝试从浏览器转到此URL时,我必须单击“继续”。否则浏览器将不会加载该页面。它给出了一个隐私错误,指出您的连接不是私有的

如何在我的Java应用程序中克服这个问题..?我希望我的软件与该网址连接,而不会出现任何错误或无需要求任何确认。


答案 1

当我使用TrustSelfSignedStrategy对象作为HttpClient的Trust材料时,问题得到了解决。

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

我使用的代码如上所示。


答案 2

对于 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);
}

推荐