ValidatorException-异常

2018-06-27 09:47:04来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

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相关问题!

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:【Java】关于Spring框架的总结 (三)

下一篇:判断ArryaList有没有重复对象的方法