Https 連接Android
在Android 中嘗試HTTPS POST 請求時,遇到「ssl 異常:不受信任的伺服器憑證」錯誤。儘管在 HTTP 下正常工作,HTTPS 呼叫失敗。
解決方案:
要繞過伺服器憑證驗證並建立HTTPS 連接,可以實現自訂信任管理器和主機名稱驗證器如下所示:
public static void trustAllHosts() { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[]{}; } public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } }}; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { e.printStackTrace(); } } // always verify the host - dont check for certificate final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } };
要使用這些設置,請將您的HTTPS 連接設定代碼修改為如下:
HttpURLConnection http = null; if (url.getProtocol().toLowerCase().equals("https")) { trustAllHosts(); HttpsURLConnection https = (HttpsURLConnection) url.openConnection(); https.setHostnameVerifier(DO_NOT_VERIFY); http = https; } else { http = (HttpURLConnection) url.openConnection(); }
以上是如何解決 Android HTTPS POST 請求中的「ssl 異常:不受信任的伺服器憑證」錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!