Home > Java > javaTutorial > How to Resolve 'ssl exception: Not trusted server certificate' Errors in Android HTTPS POST Requests?

How to Resolve 'ssl exception: Not trusted server certificate' Errors in Android HTTPS POST Requests?

Patricia Arquette
Release: 2024-12-14 01:50:09
Original
604 people have browsed it

How to Resolve

Https Connection Android

When attempting HTTPS POST requests in Android, an "ssl exception: Not trusted server certificate" error is encountered. Despite functioning properly under HTTP, HTTPS calls fail.

Solution:

To bypass server certificate verification and establish HTTPS connections, a custom Trust Manager and Hostname Verifier can be implemented as follows:

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;
    }
};
Copy after login

To use these settings, modify your HTTPS connection setup code as follows:

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();
}
Copy after login

The above is the detailed content of How to Resolve 'ssl exception: Not trusted server certificate' Errors in Android HTTPS POST Requests?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template