Skip to content
𝓒π“ͺ𝓼𝓽𝓻𝓲𝓳π“ͺ

Share the knowledge

𝓒π“ͺ𝓼𝓽𝓻𝓲𝓳π“ͺ

Share the knowledge

Setting HTTPS certificate trusted in Java

Posted on July 12, 2012September 25, 2021 By sastrija

After digging a lot in web, I found the following snippet is useful in some scenarios, where we tries to connect to a HTTPS URL from our java code.

Warning!

This solution will void the real purpose of HTTPS by disabling securities. So use it cautiously

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class CertificateManager {

    public static void main(String[] args) {
        String result = "";
        String urlString = "http://k2i.987.mywebsitetransfer.com/";
        URL url = null;
        URLConnection urlConn = null;
        String str = null;

        try {
            HostnameVerifier verifier = new HostnameVerifier() {
                @Override
                public boolean verify(String urlHostName, SSLSession session) {
                    return true;
                }
            };
            // Invoking method to trust all certificates blindly.
            try {
                trustAllHttpsCertificates();
            } catch (KeyManagementException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            HttpsURLConnection.setDefaultHostnameVerifier(verifier);

            url = new URL(urlString);
            urlConn = url.openConnection();
            urlConn.setDoInput(true);
            urlConn.setUseCaches(false);

            urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

            while (null != ((str = bufferedReader.readLine()))) {
                if (str.length() > 0) {
                    str = str.trim();
                    if (!str.equals("")) {
                        result += str;
                    }
                }
            }
            bufferedReader.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("Result :" + result);
    }

    /**
     * Creating a customized Inner class to implement the SSL TrustManager
     */
    public static class MyCustomTrustManager implements TrustManager, X509TrustManager {
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public boolean isServerTrusted(X509Certificate[] certs) {
            return true;
        }

        public boolean isClientTrusted(X509Certificate[] certs) {
            return true;
        }

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

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

    /**
     * Asking to trust all the HTTPS certificates blindly. Needs to be careful, when the HTTPS URLs are not known to us.
     *
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     * @throws Exception
     */
    private static void trustAllHttpsCertificates() throws NoSuchAlgorithmException, KeyManagementException {
        TrustManager[] trustAllCerts = new TrustManager[1];
        TrustManager myTrustManager = new MyCustomTrustManager();
        trustAllCerts[0] = myTrustManager;
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    }

}

Related

Uncategorized

Post navigation

Previous post
Next post

Comments (2)

  1. nomd says:
    March 28, 2014 at 12:00 am

    com.sun.net.ssl.TrustManager is a depricated class. Remove this import and go with javax.net.ssl.TrustManager

  2. Raghu says:
    October 7, 2014 at 12:00 am

    I am using same code but, I am getting below error: Please assist
    java.io.IOException: Server returned HTTP response code: 403 for URL

Comments are closed.

©2025 𝓒π“ͺ𝓼𝓽𝓻𝓲𝓳π“ͺ | WordPress Theme by SuperbThemes