Download file from HTTPS server using Java [duplicate]

Access an HTTPS url with Java is the same then access an HTTP url. You can always use the

URL url = new URL("https://hostname:port/file.txt");
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
// .. then download the file

But, you can have some problem when the server’s certificate chain cannot be validated.
So you may need to disable the validation of certificates for testing purposes and trust all certificates.

To do that write:

// Create a new trust manager that trust 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
try {
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}

// And as before now you can use URL and URLConnection
URL url = new URL("https://hostname:port/file.txt");
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
// .. then download the file

Leave a Comment