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
Answer from dash1e on Stack Overflow
Top answer
1 of 4
42

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
2 of 4
6

Actually I had the similar problem. I was unable to download files from HTTPS server. Then I fixed this problem with this solution:

// But are u denied access?
// well here is the solution.
public static void TheKing_DownloadFileFromURL(String search, String path) throws IOException {

    // This will get input data from the server
    InputStream inputStream = null;

    // This will read the data from the server;
    OutputStream outputStream = null;

    try {
        // This will open a socket from client to server
        URL url = new URL(search);

        // This user agent is for if the server wants real humans to visit
        String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36";

        // This socket type will allow to set user_agent
        URLConnection con = url.openConnection();

        // Setting the user agent
        con.setRequestProperty("User-Agent", USER_AGENT);

        //Getting content Length
        int contentLength = con.getContentLength();
        System.out.println("File contentLength = " + contentLength + " bytes");


        // Requesting input data from server
        inputStream = con.getInputStream();

        // Open local file writer
        outputStream = new FileOutputStream(path);

        // Limiting byte written to file per loop
        byte[] buffer = new byte[2048];

        // Increments file size
        int length;
        int downloaded = 0; 

        // Looping until server finishes
        while ((length = inputStream.read(buffer)) != -1) 
        {
            // Writing data
            outputStream.write(buffer, 0, length);
            downloaded+=length;
            //System.out.println("Downlad Status: " + (downloaded * 100) / (contentLength * 1.0) + "%");


        }
    } catch (Exception ex) {
        //Logger.getLogger(WebCrawler.class.getName()).log(Level.SEVERE, null, ex);
    }

    // closing used resources
    // The computer will not be able to use the image
    // This is a must
    outputStream.close();
    inputStream.close();
}

Use this function... Hope you will get benefited with this easy solution.

🌐
JavaBeat
javabeat.net › home › download file from http & https server using java
Download file from HTTP & HTTPS server using Java
October 10, 2019 - The example provides the simple way to download a file from the HTTP web server and store it in your local system.Also there is a way to download a file from the HTTPS server.
Discussions

Using Java To Download Files From a HTTPS URL - Stack Overflow
There are numerous sites and blogs ... https certificates to java keystore · Also, while you are testing with the browser, this will help you verify that there are no proxy issues. You should definitely check your browser's settings to determine whether or not you are going through a proxy server. You should definitely look into using HttpClient instead of java.net.URL. Here is the Apache page for HttpClient 4.2.1. Finally, if you are looking to do a file transfer via ... More on stackoverflow.com
🌐 stackoverflow.com
How can I download and save a file from the Internet using Java? - Stack Overflow
Copy/** * Downloads from a (http/https) URL and saves to a file. * Does not consider a connection error an Exception. Instead it returns: * * 0=ok * 1=connection interrupted, timeout (but something was read) * 2=not found (FileNotFoundException) (404) * 3=server error (500...) * 4=could not connect: connection timeout (no internet?) java... More on stackoverflow.com
🌐 stackoverflow.com
Https File download in java - Stack Overflow
I need to verify the contents of the word file that appears on the browser. So I downloaded the doc file. My download code is given below: private String downloader(WebElement element, String More on stackoverflow.com
🌐 stackoverflow.com
March 31, 2016
java - how to download https file from url - Stack Overflow
I have tried below two,but it's not working 1. System.setProperty("com.sun.security.enableAIAcaIssuers","true"); 2. updated my java version from 1.7 to 1.8.0_121 · download("https://www.treasury.gov/ofac/downloads/sdn.xml","D:\\AML_Files\\Download_Check\\sdnList.xml"); public static void ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Vogella
vogella.com › tutorials › JavaNetworking › article.html
Java Networking - Using HttpURLConnection to download files from the Internet - Tutorial
package com.vogella.java.introduction; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class DownloadWebpageExample { private static final String newLine = System.getProperty("line.separator"); public static void main(String[] args) { try { URL url = new URL("https://www.vogella.com/"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); String readStream = readStream(con.getInputStream()); // Give output for the command line System.out.println(r
Top answer
1 of 3
3

You may be having certificate issues. This is typically the problem I have encountered in the past when working with HTTPS connections in Java.

First, you should check and see if the URL to which you are attempting to connect has a signed certificate by a well-known trusted root CA, and is valid (not expired).

I would recommend opening the URL in your browser and checking the certificate information.

Just a FYI, there may be a disconnect between the Trusted Root CAs recognized by your browser and those recognized by Java. Here is another Stackoverflow question about how to get those recognized by Java: How can I get a list of trusted root certificates in Java?

If this is a self-signed certificate, then there are hoops you will need to jump through regarding importing it into and using a local Keystore. There are numerous sites and blogs that guide you through doing this, here is one such blog (not mine): Adding self-signed https certificates to java keystore

Also, while you are testing with the browser, this will help you verify that there are no proxy issues. You should definitely check your browser's settings to determine whether or not you are going through a proxy server.

You should definitely look into using HttpClient instead of java.net.URL. Here is the Apache page for HttpClient 4.2.1.

Finally, if you are looking to do a file transfer via HTTP or HTTPS, you may want to consider WebDAV.

I have used Jakarta Slide WebDAV Client for this in the past. Unfortunately, it looks like Slide is retired at this point, but there are alternatives you can find with a little bit of searching.

ADDITION

I copied down your source code sample and looked at it more closely. Looks like you set properties for http, but not https.

HTTPS has separate properties:

  • https.proxyHost
  • https.proxyPort

Try setting:

System.setProperty("https.proxyHost","trproxy.rwe.com") ; 
System.setProperty("https.proxyPort", "443") ; 

Look at section 2.2 on Oracle's Java Networking and Proxies.

http://docs.oracle.com/javase/6/docs/technotes/guides/net/proxies.html

2 of 3
1

Looks like your problem could be with the proxy. It should also support https. Also, you should use HttpClient 4 for downloading the files, its a mature library for making http connections.

🌐
Matjazcerkvenik
matjazcerkvenik.si › developer › java-download-file-via-http.php
Java Download File via HTTP - Matjaž Cerkvenik
At the end we will print the size of transfered file - it should be the same as expected size. But sooner or later the server will empty the cache and the Java will loop endlesly reading zero bytes from the input stream. // url=http://www.example.com/testFile.zip // localFile=/path/to/testFile.zip public static void download(String url, String localFile) throws Exception { System.out.println("Downloading " + localFile); URL website = new URL(url); URLConnection connection = website.openConnection(); ReadableByteChannel rbc = Channels.newChannel(connection.getInputStream()); FileOutputStream fo
🌐
Coderanch
coderanch.com › t › 458144 › java › Downloading-files-HTTPS-server
Downloading files from a HTTPS server (Java in General forum at Coderanch)
And what happens if you try to connect using URL, URLConnection and HttpsURLConnection as Sebastian suggested? SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6 How To Ask Questions How To Answer Questions ... Hand shake exception is caused due to java not being to handle SSL connections by default.
🌐
CodingTechRoom
codingtechroom.com › question › download-file-https-server-java
How to Download a File from an HTTPS Server Using Java - CodingTechRoom
import java.io.BufferedInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; public class FileDownloader { public static void main(String[] args) { String fileURL = "https://example.com/file.zip"; String saveFilePath = "C:/Downloads/file.zip"; try { downloadFile(fileURL, saveFilePath); } catch (IOException e) { e.printStackTrace(); } } public static void downloadFile(String fileURL, String saveFilePath) throws IOException { URL url = new URL(fileURL); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(
Find elsewhere
🌐
Baeldung
baeldung.com › home › java › java io › download a file from an url in java
Download a File From an URL in Java | Baeldung
January 8, 2024 - In this tutorial, we’ll see several methods that we can use to download a file. We’ll cover examples ranging from the basic usage of Java IO to the NIO package as well as some common libraries like AsyncHttpClient and Apache Commons IO.
🌐
CodingTechRoom
codingtechroom.com › question › https-example-com-download-files-https-java
How to Download Files from HTTPS URLs Using Java - CodingTechRoom
import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; public class FileDownloader { public static void main(String[] args) { String fileURL = "https://example.com/file.txt"; String saveDir = "C:/downloads/file.txt"; try { URL url = new URL(fileURL); URLConnection connection = url.openConnection(); InputStream inputStream = connection.getInputStream(); Path targetPath = Paths.get(saveDir); Files.copy(inputStream, targetPath, StandardCopyOption.REPLACE_EXISTING); inputStream.close(); System.out.println("File downloaded to " + saveDir); } catch (IOException e) { e.printStackTrace(); } }
🌐
Zachary Betz
zwbetz.com › download-a-file-over-https-using-apache-commons-fileutils-copyurltofile
Download a File Over HTTPS Using Apache Commons' FileUtils | Zachary Betz
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.X509Certific
🌐
TutorialKart
tutorialkart.com › java › java-download-file-from-url
How to Download File from URL in Java?
January 10, 2023 - import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import org.apache.commons.io.FileUtils; /** * Java Example Program to download file from website */ public class DownloadFromURL { public static void main(String[] args) { try { URL url = new URL("https://www.tutorialkart.com/"); File destination_file = new File("files/tutorialkart.html"); FileUtils.copyURLToFile(url, destination_file); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
🌐
Attacomsian
attacomsian.com › blog › java-download-save-file-from-internet
How to download and save a file from Internet in Java
December 11, 2019 - The Apache Commons IO library provides FileUtils.copyURLToFile() method to download and save a file from the Internet as shown below: try { // internet URL URL url = new URL("https://i.imgur.com/mtbl1cr.jpg"); // local file path File file = ...
🌐
Stack Overflow
stackoverflow.com › questions › 32944655 › https-file-download-in-java
Https File download in java - Stack Overflow
March 31, 2016 - tate: " + this.mimicWebDriverCookieState); if (this.mimicWebDriverCookieState) { localContext.setAttribute(ClientContext.COOKIE_STORE, mimicCookieState(this.driver.manage().getCookies())); } //core downloading part HttpGet request = new HttpGet(fileToDownload.toURI()); LOG.info("Sending GET request for: " + request.getURI()); HttpResponse response = client.execute(request, localContext); this.httpStatusOfLastDownloadAttempt = response.getStatusLine().getStatusCode(); LOG.info("HTTP GET request status: " + this.httpStatusOfLastDownloadAttempt); File downloadedFile = new File(this.localDownloadP
🌐
Coderanch
coderanch.com › t › 565698 › java › Download-file-https-website
Download a file from a https: website (I/O and Streams forum at Coderanch)
January 27, 2012 - Here is the code: ----------- public static void main(String args[]) throws IOException { java.io.BufferedInputStream in = new java.io.BufferedInputStream( new java .net .URL("https://www.fededirectory.frb.org/FedACHdir.txt").openStream()); java.io.FileOutputStream fos =new java.io.FileOutputStream("c:/bankInfo.txt"); java.io.BufferedOutputStream bout = new BufferedOutputStream(fos, 1024); byte[] data = new byte[1024]; int x = 0; while ((x = in.read(data, 0, 1024)) >= 0) { bout.write(data, 0, x); } bout.close(); in.close(); System.out.println("File Downloaded"); } ----------- Thanks
🌐
Java67
java67.com › 2023 › 09 › how-to-download-file-using-http-in-java.html
How to download a file using HTTP in Java? Example | Java67
This is done in the example code above by using the try-with-resources statement, which automatically closes the instances even if an exception is thrown. In summary, downloading a file using Java requires careful consideration of error handling, response code handling, resource management, and timeout settings.
🌐
Alvin Alexander
alvinalexander.com › blog › post › java › simple-https-example
A Java HTTPS client example | alvinalexander.com
August 1, 2024 - Sure, here’s the source code for an example Java HTTPS client program I just used to download the contents of an HTTPS (SSL) URL.
🌐
Coderanch
coderanch.com › t › 328302 › java › Login-Download-file-https
Login and Download file over https (Java in General forum at Coderanch)
<a href="http://forums.hotjoe.com/forums/list.page" target="_blank" rel="nofollow">Java forums using Java software</a> - Come and help get them started. ... I looked at HttpClient and tried the following example. But somehow I can't connect and it keeps giving error. Here is the code I am trying: but I keep getting the following error. Can someone please help me out here: If I open a browser and copy the following in URL it directly logs me in https://my.domain.com/bin/default.asp&UserId=userid?Password=password How can I log-in throug my script.
🌐
Stack Overflow
stackoverflow.com › questions › 54284929 › how-to-download-https-file-from-url
java - how to download https file from url - Stack Overflow
I have tried below two,but it's not working 1. System.setProperty("com.sun.security.enableAIAcaIssuers","true"); 2. updated my java version from 1.7 to 1.8.0_121 · download("https://www.treasury.gov/ofac/downloads/sdn.xml","D:\\AML_Files\\Download_Check\\sdnList.xml"); public static void ...