How to Trust All Certificates or ByPass Certificates for HttpURLConnection in Android

For security reason some time we as android developer get rest api with 'https' which work fine without hack if server has CA certificate successfully installed. if any problem with CA certificate the we get SSLHandshakeExcetion when we try to get data from 'https' API. This is road blocker for developer to complete app development on time. So friend don't worry for this, We can bypass SSL certificate  while writing application code and in debug mode.



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

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) {
    }
}

You should call this method before every "https" rest api call . After this code you need call your "https" API without any break but one thing you need to take care that you need to remove this code while you prepare to upload build to play store .
Hope this will help you. Comment below for any query.

Cheer!!


Previous
Next Post »

1 comments:

Click here for comments
30 July 2018 at 12:39 ×

I get a "method does not support a request body: GET" exception

Congrats bro Jordan Thompson you got PERTAMAX...! hehehehe...
Reply
avatar