HttpURLConnection繞過HTTPS的SSL驗證

(這個jdk環境須要是1.8,以上)。session

直接在類裏面加一個static代碼塊url

 1 static {  2         try {  3  trustAllHttpsCertificates();  4             HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {  5                 public boolean verify(String urlHostName, SSLSession session) {  6                     return true;  7  }  8  });  9         } catch (Exception e) { 10  } 11     }

  在調用以下方法:spa

 1 private static void trustAllHttpsCertificates() throws NoSuchAlgorithmException, KeyManagementException {  2         TrustManager[] trustAllCerts = new TrustManager[1];  3         trustAllCerts[0] = new TrustAllManager();  4         SSLContext sc = SSLContext.getInstance("SSL");  5         sc.init(null, trustAllCerts, null);  6  HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());  7  }  8 
 9     private static class TrustAllManager implements X509TrustManager { 10         public X509Certificate[] getAcceptedIssuers() { 11             return null; 12  } 13 
14         public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException { 15  } 16 
17         public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException { 18  } 19     }

這樣就應該沒有問題了。code

相關文章
相關標籤/搜索