Java Disable HTTPS Certificate Validation


While working with HTTP clients in java, many times we get a certificate validation exception as given below.

Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

The above exception can be caused due to a self-signed certificate or expired certificate as the client is unable to validate certificates, this exception can also occur behind corporate internet proxies.

If someone wants to disable this exception in Java programs then this can be done programmatically by creating a custom socket factory and optionally creating a host names varifire.

If someone using HttpsURLConnection class then this disable certificate validation as given below.

Java Example to disable HTTPS certificate validation

If you are using Apache HTTP client version 4.5 or above then you can disable certificate validation using the following code.

HttpClient httpClient = HttpClients.custom()
                .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, TrustAllStrategy.INSTANCE).build())
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .build();

Inside a static block define TrustManager as given below. This will disable issuer certificate chain validation as the below code will return null for the issuer certificate.

Then create one SSLContext using this TrustManager object and set HttpsURLConnection socket factory from created SSLContext object.

Optionally you can also disable host verification using HostnameVerifier class as given below.

public class UrlConnectionClient {
    static {
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

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

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

        SSLContext sc = null;
        try {
            sc = SSLContext.getInstance("SSL");
        } catch (NoSuchAlgorithmException e) {
            System.out.println(e.getMessage());
        }
        try {
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
        } catch (KeyManagementException e) {
            System.out.println(e.getMessage());
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        // Optional 
        // Create all-trusting host name verifier
        HostnameVerifier validHosts = new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        };
        // All hosts will be valid
        HttpsURLConnection.setDefaultHostnameVerifier(validHosts);

    }

    public void printResponse(String url) {
        HttpsURLConnection conn = null;
        try {
            URL myUrl = new URL(url);
            conn = (HttpsURLConnection) myUrl.openConnection();
            conn.setRequestMethod("GET");
            StringBuilder content;
            try (BufferedReader in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()))) {
                String line;
                content = new StringBuilder();
                while ((line = in.readLine()) != null) {
                    content.append(line);
                    content.append(System.lineSeparator());
                }
            }
            System.out.println(content.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            conn.disconnect();
        }
    }

    public static void main(String[] args){
        UrlConnectionClient client = new UrlConnectionClient();
        client.printResponse("https://sqa-noc-alb-186464997.us-east-1.elb.amazonaws.com/masterservice/api/v1/");
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.