[ 登录 ] - [ 注册 ] | 推广返现20% 数据无忧_无忧代理IP最新上线 | 代码示例DEMO | IP测试视频 |

sun.security.validator.ValidatorException: PKIX path building failed

作者:数据无忧   时间:2020-09-18 13:24:53
无忧代理IP推广返现活动 Java做爬虫处理HTTPS链接时报错sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

这个是因为程序未处理证书才会报这个错误,解决办法只需要信任证书即可。添加下面的工具类:

// 信任所有证书    
public class TrustCertsUtil {
public static void trustAllHttpsCertificates() {
// 如果爬虫请求HTTPS网址,必须加入这两行
System.setProperty("jdk.http.auth.proxying.disabledSchemes", "");
System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
try {
       javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
       javax.net.ssl.TrustManager tm = new MITM();
       trustAllCerts[0] = tm;
       javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("TLS");
       sc.init(null, trustAllCerts, null);
       javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
System.err.println("【DATA5U】设置证书出错,原因:" + e.getMessage());
}
}
   static class MITM implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
       public java.security.cert.X509Certificate[] getAcceptedIssuers() {
           return null;
       }
       public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
           return true;
       }
       public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
           return true;
       }
       public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
               throws java.security.cert.CertificateException {
           return;
       }
       public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
               throws java.security.cert.CertificateException {
           return;
       }
   }
}


然后再项目的main方法中加入这行代码即可:TrustCertsUtil.trustAllHttpsCertificates();

如果项目使用的是HttpClient,上面的方法还不见效,请参考  HttpClient跳过证书的方法


福利:现在购买代理IP,购买后联系客服直接   返现20%   到你的支付宝(最低35元,最高1440元)
无忧代理IP(www.data5u.com)原创文章,转载请注明出处。

微信公众号
关注微信公众号