解决PKIX path building failed异常问题

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
 at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174)
 at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1591)
 at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:187)
 at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:181)

 

在使用

org.apache.http.impl.client.HttpClients.createDefault()方法获取CloseableHttpClient对象时,由于服务器上的jdk版本是1.6,本地用的是jdk是1.8,导致打包后放到服务器上调用第三方接口时报 sun.security.validator.ValidatorException: PKIX path building failed异常。经排查处理,用以下方法进行解决了。

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import common.Logger;

public class SkipHttpsUtil {

   private static Logger logger = Logger.getLogger(SkipHttpsUtil.class);
    //绕过证书
    public static HttpClient wrapClient() {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
 
                public void checkClientTrusted(X509Certificate[] arg0,
                        String arg1) throws CertificateException {
                }
 
                public void checkServerTrusted(X509Certificate[] arg0,
                        String arg1) throws CertificateException {
                }
            };
            ctx.init(null, new TrustManager[] { tm }, null);
            SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(
                    ctx, NoopHostnameVerifier.INSTANCE);
            CloseableHttpClient httpclient = HttpClients.custom()
                    .setSSLSocketFactory(ssf).build();
            return httpclient;
        } catch (Exception e) {
            return HttpClients.createDefault();
        }
    } 
}

后面在想要获取CloseableHttpClient对象时直接使用下面代码进行调用就行了

CloseableHttpClient httpclient =  (CloseableHttpClient)SkipHttpsUtil.wrapClient();
发布了4 篇原创文章 · 获赞 3 · 访问量 6821
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览