Tutorials Android How to Trust All Certificates for HttpURLConnection in Android

How to Trust All Certificates for HttpURLConnection in Android

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) {
    }
}
	
Total
0
Shares
Previous Post
Appium Code Snippets

Sample env.rb File for Setting up Android Testing Using Appium and Ruby

Next Post

How to Determine Android Screen Size Width and Height

Related Posts
By clicking “Allow All”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. Cookie Notice
Allow All