請求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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM