首页 >Java >java教程 >Android 中如何处理未经验证的 HTTPS 连接?

Android 中如何处理未经验证的 HTTPS 连接?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-12-10 16:46:16220浏览

How Can I Handle Unverified HTTPS Connections in Android?

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

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn