JAVA 忽略 HTTPS 驗證

  • 11058
  • 0

摘要:JAVA 忽略 HTTPS 驗證

這個問題,大概是出現在連線到測試機時,因為該測試機並沒有https驗證,但又要以https網址為開頭,

而連線過去的時候,由於該測試機並沒有第三方驗證,但又要讓他過關,所以才需要忽略https驗證。

 

這時候Java如果連到https,但沒忽略的話,會出現下面的Exception

 

sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
 
為了這個問題Google了一下網路文章,下面這篇文章,寫的相當的話,因此,我使用他的方式。
 
但用了最下面的方法,仍不可行。
所以我兩個方法都用。
就過關了。
以下是兩個方法都加之後的程式碼方法。
 
    /**
         * 忽略驗證https
         */
    public static void igoreVerify() throws Exception
    {

        ignoreVerifyHttpsTrustManager();
        ignoreVerifyHttpsHostName();
    }

    /**
         * 忽略驗證https
         */
    public static void ignoreVerifyHttpsHostName()
    {
        HostnameVerifier hv = new HostnameVerifier()

        {

              public boolean verify(String urlHostName, SSLSession session)

              {

                     System.out.println("Warning: URL Host: "+urlHostName+" vs. "+session.getPeerHost());

                     return true;

              }

        };

        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    }

    /**
         * 忽略驗證https
         */
    public static void ignoreVerifyHttpsTrustManager() throws Exception
    {
        TrustManager[] trustAllCerts = new TrustManager[] {
                new X509TrustManager(){
                    public java.security.cert.X509Certificate[] getAcceptedIssuers()
                    {
                            return null;
                    }

                    public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
                    {
                    }

                    public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
                    {
                    }
                }
        };

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }