• 那是从何处传来的钟声呢?偶尔听到那钟声,平添一份喜悦与向往之情。

使用HttpClient发送Https请求时,出现异常PKIX path building failed: sun.security.provider.certpath.SunCertPathBuil

后端 Nanait 3年前 (2020-12-09) 1920次浏览 已收录 0个评论 扫描二维码

使用HttpClient发送Https请求时,出现异常为:
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
出现这个异常的原因为,客户端向服务器发送 https 请求时,会验证服务端的证书状态,可以设置信任所有证书,绕过这一步。
查看HttpClient官方文档,示例如下:
在这里插入图片描述
在这里插入图片描述
可以直接使用 SSLContext 来构建实例,代码如下:

<code class="has-numbering">public static Closeable<a href="http://jinwei.fun/mdzztag/httpclient" title="查看更多关于 HttpClient 的文章" target="_blank">HttpClient</a> createSSLClientDefault() {
        try {
            //使用 loadTrustMaterial() 方法实现一个信任策略,信任所有证书
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                // 信任所有
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            //NoopHostnameVerifier 类:  作为主机名验证工具,实质上关闭了主机名验证,它接受任何
            //有效的 SSL 会话并匹配到目标主机。
            HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
            return <a href="http://jinwei.fun/mdzztag/httpclient" title="查看更多关于 HttpClient 的文章" target="_blank">HttpClient</a>s.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        return <a href="http://jinwei.fun/mdzztag/httpclient" title="查看更多关于 HttpClient 的文章" target="_blank">HttpClient</a>s.createDefault();

    }
</code>

如何直接使用这个方法返回的 client 对象去发送请求即可


何处钟 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:使用 HttpClient 发送 Https 请求时,出现异常 PKIX path building failed: sun.security.provider.certpath.SunCertPathBuil
喜欢 (13)
[15211539367@163.com]
分享 (0)

您必须 登录 才能发表评论!