Home > Java > javaTutorial > How to Bypass Untrusted Server Certificates When Establishing HTTPS Connections on Android?

How to Bypass Untrusted Server Certificates When Establishing HTTPS Connections on Android?

DDD
Release: 2024-12-10 16:25:12
Original
903 people have browsed it

How to Bypass Untrusted Server Certificates When Establishing HTTPS Connections on Android?

HTTPS Connection Establishment on Android

When attempting to establish an HTTPS connection on Android, developers may encounter an exception related to an untrusted server certificate. To address this, one may consider accepting the server certificate.

Trust All Hosts

One approach to bypass certificate verification is to trust all hosts, effectively disabling the check. This can be achieved by implementing a custom HostnameVerifier and a TrustManager.

// Hostname verifier that always returns true
HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
    @Override
    public boolean verify(String hostname, SSLSession session) {
        return true;
    }
};

// Trust manager that accepts all certificates
TrustManager[] trustAllCerts = new TrustManager[]{
    new X509TrustManager() {
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) {}

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) {}
    }
};
Copy after login

Next, initialize the SSLContext and apply the trust manager and hostname verifier.

SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
Copy after login

Example Usage

When creating an HTTP connection, check the protocol and apply the aforementioned configuration if it's HTTPS.

HttpURLConnection http = null;
String url = "https://example.com";

if (url.toLowerCase().equals("https")) {
    trustAllHosts();
    HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
    https.setHostnameVerifier(DO_NOT_VERIFY);
    http = https;
} else {
    http = (HttpURLConnection) url.openConnection();
}
Copy after login

The above is the detailed content of How to Bypass Untrusted Server Certificates When Establishing HTTPS Connections on Android?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template