Skip to main content

Download a file over HTTPS using Apache Commons' FileUtils

Published: 2019-01-30 | Lastmod: 2019-07-05

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: