ValidatorException-异常

Java在发送Https请求的时候,不可避免的会发生SSL证书认证失败

错误信息:sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

错误原因是因为发送Https请求的时候 SSL证书认证失败

事发现场:在使用HttpClient调用支付宝的Https接口时发生的错误

解决方法:创建一个HttpSSL类,代码如下

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;

public class HttpSSL {
    private static void trustAllHttpsCertificates() throws Exception {
        javax.net.ssl.TrustManager[] trustAllCerts = new 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());
    }
    
    
    public static void solveSSL() throws Exception{
          trustAllHttpsCertificates();
          HostnameVerifier hv = new HostnameVerifier() {
              public boolean verify(String urlHostName, SSLSession session) {
                  
                  return true;
              }
          };
          HttpsURLConnection.setDefaultHostnameVerifier(hv);
    }
    
    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;
        }
    }
}

使用方式,在发送Https请求之前,调用该类的 solveSSL()方法忽略证书认证问题

 

OK,基本能解决SSL认证失败的问题了!

 

本人唯一QQ:1132017151

欢迎来讨论Java相关问题!

 

posted @ 2018-06-25 16:16  浮夸半生『  阅读(1725)  评论(0编辑  收藏  举报