Java访问https时解决sun.security.validator.ValidatorException: PKIX path building failed 问题

Posted 贝加尔湖畔╭

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java访问https时解决sun.security.validator.ValidatorException: PKIX path building failed 问题相关的知识,希望对你有一定的参考价值。

转自:https://www.cnblogs.com/chenzhanxun/articles/4463151.html

今天刚学了网络编程在网上尝试下载东西时报:

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

一阵搜错终于解决了,在这里记录下代码:具体请到上面的原作者阅读!

static HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String urlHostName, SSLSession session) {
            System.out.println("Warning: URL Host: " + urlHostName + " vs. "
                               + session.getPeerHost());
            return true;
        }
    };
 
 private static void trustAllHttpsCertificates() throws Exception {
 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("SSL");
 sc.init(null, trustAllCerts, null);
 javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc
 .getSocketFactory());
 }

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

2)在访问https资源前,调用

 

trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(hv);

以上是关于Java访问https时解决sun.security.validator.ValidatorException: PKIX path building failed 问题的主要内容,如果未能解决你的问题,请参考以下文章

Java访问https时解决sun.security.validator.ValidatorException: PKIX path building failed 问题

Java生成证书工具类 InstallCert.java解决httpClient访问https出错:PKIX path building failed

Java访问HTTPS时证书验证问题

Java的HttpClient如何去支持无证书访问https

java调用webservice访问时,有iis认证怎么解决

java调用webservice访问时,有iis认证怎么解决