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中文网其他相关文章!