请求https接口时的SSLHandshakeException

最近,项目里请求https接口出现了以下异常问题:

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

问了度娘之后,有两种解决方案:

  1、导入证书

    传送门:https://blog.csdn.net/hzhahsz/article/details/84862285?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-3.vipsorttest&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromMachineLearnPai2%7Edefault-3.vipsorttest

  2、忽略证书验证

    网上方法很多,我使用了以下方法,亲测有效: 

CloseableHttpClient client = HttpUtil.getIgnoeSSLClient();

/**
 * 获取忽略证书验证的client
 *
 * @return
 * @throws Exception
 */
public static CloseableHttpClient getIgnoeSSLClient() throws Exception {
    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            return true;
        }
    }).build();

    //创建httpClient
    CloseableHttpClient client = HttpClients.custom().setRedirectStrategy(new LaxRedirectStrategy())
            .setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
    return client;
}

 

posted @ 2021-05-14 11:03  *Abby  阅读(5556)  评论(0编辑  收藏  举报