http client SunCertPathBuilderException unable to find valid certification path to requested target

使用httpclinet 发送请求时出现如下异常。

        at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387) ~[?:1.8.0_45]
        at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292) ~[?:1.8.0_45]
        at sun.security.validator.Validator.validate(Validator.java:260) ~[?:1.8.0_45]
        at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324) ~[?:1.8.0_45]
        at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229) ~[?:1.8.0_45]
        at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124) ~[?:1.8.0_45]
        at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1460) ~[?:1.8.0_45]
        ... 91 more
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) ~[?:1.8.0_45]
        at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:131) ~[?:1.8.0_45]
        at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280) ~[?:1.8.0_45]
        at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382) ~[?:1.8.0_45]
        at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292) ~[?:1.8.0_45]
        at sun.security.validator.Validator.validate(Validator.java:260) ~[?:1.8.0_45]
        at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324) ~[?:1.8.0_45]
        at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229) ~[?:1.8.0_45]
        at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124) ~[?:1.8.0_45]
        at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1460) ~[?:1.8.0_45]

原来的请求方式

CloseableHttpClient httpclient = HttpClients.createDefault();

问题分析

异常信息提示的很明确,本地的认证证书有问题。可能是未启用jdk ssl 证书也有可能是过期。

信任请求

信任所有的请求

 SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, (chain, authType) -> true);
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(),
                                                                              NoopHostnameVerifier.INSTANCE);
    CloseableHttpClient         httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

总结

上述解决方案相对比较暴力,在不考虑安全的情况下信任所有请求,而有的环境对安全要求比较高时,建议通过调整证书的方式来解决。

http client SunCertPathBuilderException unable to find valid certification path to requested target

上一篇:Django 使用正则匹配URL 并将匹配成功的值传递给视图函数


下一篇:上传的文件尺寸超过upload_max_filesize文件中定义的php.ini值的解决方法