Download a File Over HTTPS Using Apache Commons' FileUtils

Published: Jan 30, 2019
Updated: May 3, 2021

In some of our selenium tests, we download a PDF file generated by our app and then inspect it. This works fine locally since the app URL is http. But in our CI environment, everything is over https. So we had to do some tweaking before calling FileUtils.copyURLToFile. Below is a stripped down version of our solution:

// Create a new trust manager that trusts all certificates
TrustManager[] trustAllCerts = new TrustManager[]{
    new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {
        }
    }
};

// Activate the new trust manager
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

// Open connection to the URL
URL url = new URL("https://example.com");
URLConnection connection = url.openConnection();

// Download the file 
FileUtils.copyURLToFile(connection.getURL(), new File("/path/to/file"));

Credits to these stackoverflow answers: