Arthur's Blog

Ignore certificate for HttpURLConnection in Android

1 year ago

This code has been scraped together from various sources around the web when I tried to figure out how to stop validation of the SSL certificate when using HttpURLConnection in Android.  The following code disables SSL certificate checking for any new instances of HttpsUrlConnection;

    /**
     * Disables the SSL certificate checking for new instances of {@link HttpsURLConnection} This has been created to
     * aid testing on a local box, not for use on production.
     */
    private static void disableSSLCertificateChecking() {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                // Not implemented
            }

            @Override
            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                // Not implemented
            }
        } };

        try {
            SSLContext sc = SSLContext.getInstance("TLS");

            sc.init(null, trustAllCerts, new java.security.SecureRandom());

            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

HttpsUrlConnection extends HttpUrlConnection so you should be able to call all of the same methods that you were previously using.  Now, call the above method, and then create a new instance of HttpsUrlConnection and use that in exactly the same way as you were using the HttpUrlConnection.