Android 中未經驗證的 Https 連線
執行 HTTP(S) 要求時,如果遇到「SSL 異常不受信任的伺服器憑證」錯誤使用HTTPS時,您可能需要處理伺服器憑證驗證
解決方案:
要繞過憑證驗證並信任所有伺服器,可以實現以下程式碼:
// Ignore hostname verification HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; // Trust all certificates TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[] {}; } } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { e.printStackTrace(); } // Open the connection, setting hostname verification to false and using the custom trust manager HttpURLConnection http = null; if (url.getProtocol().toLowerCase().equals("https")) { HttpsURLConnection https = (HttpsURLConnection) url.openConnection(); https.setHostnameVerifier(DO_NOT_VERIFY); http = https; } else { http = (HttpURLConnection) url.openConnection(); }
使用此程式碼,對於正常的HTTP 和HTTPS 連接,都會跳過SSL 憑證驗證。
以上是Android 中如何處理未經驗證的 HTTPS 連線?的詳細內容。更多資訊請關注PHP中文網其他相關文章!