2012-08-29 142 views
7

當我想打開一個HTTPS連接時,我得到SSL異常。如何設置HttpURLConnection以便對此異常不敏感?禁用HTTPS連接的SSL證書驗證?

我的代碼是:

private String getData() { 
    String response = null; 
    String connection = "https://www.kamalan.com/"; 

    try { 
     URL url = new URL(connection); 
     Log.i(TAG, "Try to open: " + connection); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 

     int responseCode = conn.getResponseCode(); 
     Log.i(TAG, "Response code is: " + responseCode); 
     if (responseCode == HttpURLConnection.HTTP_OK) { 
      BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
      if (in != null) { 
       StringBuilder strBuilder = new StringBuilder();    
       int ch = 0; 
       while ((ch = in.read()) != -1) 
        strBuilder.append((char) ch); 

       // get returned message and show it 
       response = strBuilder.toString(); 
       Log.i("JSON returned by server:", response); 
      } 

      in.close(); 

     } else { 
      Log.e(TAG, "Couldn't open connection in getResepiItems()"); 
     } 
    } catch (SSLException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    return response; 
} 
+0

什麼是logcat的說,下面的方法是什麼? –

+0

@Morrison Chang這是log cat中的錯誤'導致:java.security.cert.CertificateException:java.security.cert.CertPathValidatorException:未找到認證路徑的信任錨'。 –

+1

你看到這個SO帖子:http: //stackoverflow.com/questions/6825226/trust-anchor-not-found-for-android-ssl-connection? –

回答

0

按照下面的方法,它爲我工作。

 URL url = new URL("Your URL"); 
     HttpsURLConnection urlConnection =(HttpsURLConnection) url.openConnection(); urlConnection.setSSLSocketFactory(SSLCertificateSocketFactory.getInsecure(0, null)); 
     urlConnection.setHostnameVerifier(getHostnameVerifier()); 
     InputStream is = urlConnection.getInputStream(); 
     OutputStream os = new FileOutputStream(downloadedFile); 
     byte[] data = new byte[1024]; 
     int count; 
     while ((count = is.read(data)) != -1) { 
      os.write(data, 0, count); 
     } 
     os.flush(); 
     os.close(); 
     is.close(); 

用於設置主機名

private HostnameVerifier getHostnameVerifier() { 
     HostnameVerifier hostnameVerifier = new HostnameVerifier() { 
      @Override 
      public boolean verify(String hostname, SSLSession session) { 
       HostnameVerifier hv = 
         HttpsURLConnection.getDefaultHostnameVerifier(); 
       return hv.verify("com.example.com", session); 
      } 
     }; 
     return hostnameVerifier; 
    } 
+0

它的工作原理如何?爲什麼?所有這些廢話只不過是針對固定主機名來驗證會話。沒有說明這一點,如果有的話。不要對未引用的文本使用引號格式, – EJP