StackTips
 2 minutes

How to Trust All Certificates for HttpURLConnection in Android

By Editorial @stacktips, On Sep 17, 2023 Android 2.91K Views

The following code snippet will help you to disables the SSL certificate checking for new instances of HttpsURLConnection in Android.

Note: You can use this code for testing purpose only and remove when moving to production. Trusting all certificate in production will expose your box for hackers.

public void trustAllCertificates() {
    try {
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                        X509Certificate[] myTrustedAnchors = new X509Certificate[0];
                        return myTrustedAnchors;
                    }

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

                    @Override
                    public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    }
                }
        };

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
    } catch (Exception e) {
    }
}
	
stacktips avtar

Editorial

StackTips provides programming tutorials, how-to guides and code snippets on different programming languages.