关于java:记高版本JDK访问HTTPS出现证书错误PKIX-path-building-failed

53次阅读

共计 1529 个字符,预计需要花费 4 分钟才能阅读完成。

公司有个我的项目应用了 JDK17, 须要拜访内部的 https 服务的 http get 拜访接口。
代码如下

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = httpClient.execute(httpGet);

简简单单的申请呈现了以下谬误, 一脸懵.
查问了 google, 说是要下载证书到 jre/lib/security 下;
无奈 mac 的 chrome 及 safari 都无奈导出证书;
只能本人钻研看报错信息了, 次要谬误起因在于新版本 JDK 的 ssl 验证报错:

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 java.base/sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:439)
    at java.base/sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:306)
    at java.base/sun.security.validator.Validator.validate(Validator.java:264)
    at java.base/sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:231)
    at java.base/sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:132)
    at java.base/sun.security.ssl.CertificateMessage$T12CertificateConsumer.checkServerCerts(CertificateMessage.java:638)
    ... 24 more

因而只须要重写 X509TrustManager, 并注入到 httpClient 即可
X509TrustManager 能够本人实现, 也能够应用现成实现,
比方 cn.hutool.core.net.DefaultTrustManager


            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new DefaultTrustManager();
            ctx.init(null, new TrustManager[] {tm}, null);
            SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
            CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(ssf).build();
            return httpclient;

应用该 httpclient 执行就能够绕过 ssl 的证书检测。

正文完
 0