2011-09-16 80 views
4

我試圖讓Java接受通過HTTPS的所有證書。這是爲了測試目的。之前我得到一個證書未找到錯誤。但是,在我的代碼之前添加以下代碼後,我得到一個HTTPS hostname wrong: should be <sub.domain.com>錯誤。問題是我的網址IS那個網址。我如何解決這個問題?以下是我已經加入到嘗試解決該問題的代碼..讓Java接受通過HTTPS的所有證書

 // Create a trust manager that does not validate certificate chains 
    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) { 
      } 
     } 
    }; 

    // Install the all-trusting trust manager 
    try { 
     SSLContext sc = SSLContext.getInstance("SSL"); 
     sc.init(null, trustAllCerts, new java.security.SecureRandom()); 
     HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); 
    } catch (Exception e) { 
    } 

回答

6

您需要設置一個HostNameVarifier也 例:

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

public class TrustAllHostNameVerifier implements HostnameVerifier { 

    public boolean verify(String hostname, SSLSession session) { 
     return true; 
    } 

} 

然後

httpsConnection.setHostnameVerifier(new TrustAllHostNameVerifier()); 
+2

剛擡起頭來。這可能會導致MTM攻擊,在這種情況下證書不會被可信任的CA驗證。除非至少有一個對端通過身份驗證,否則SSL不安全。 – cherit

+1

的確如此,但是OP明確表示需要用於測試目的 –