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.

🌐
CodeJava
codejava.net › java-se › networking › use-httpurlconnection-to-download-file-from-an-http-url
Java HttpURLConnection to download file from an HTTP URL
July 18, 2019 - Then we extract the file name either from the HTTP header Content-Disposition (in case the URL is an indirect link), or from the URL itself (in case the URL is the direct link). We also print out some debugging information like Content-Type, Content-Disposition, Content-Length and file name.And ...
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.

🌐
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(); } } }
🌐
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 - Finally, we’ll talk about how ... basic API we can use to download a file is Java IO. We can use the URL class to open a connection to the file we want to download....
🌐
JavaBeat
javabeat.net › home › download file from http & https server using java
Download file from HTTP & HTTPS server using Java
October 10, 2019 - package com.service; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.nio.charset.MalformedInputException; public class TestClass { public static void main(String[] args) { URL url = null; URLConnection con = null; int i; try { url = new URL("https://localhost:8080/AppName/FileName.txt"); con = url.openConnection(); File file = new File( "C:\Foldername\Address.txt"); BufferedInputStream bis = new BufferedInputStream( con.getIn
🌐
Vogella
vogella.com › tutorials › JavaNetworking › article.html
Java Networking - Using HttpURLConnection to download files from the Internet - Tutorial
For example, your can send a get request to "https://tinyurl" or https://tr.im" and receive a short version of the Url you pass as parameter. The following will demonstrate how to call the get service from "https://TinyUrl" or "https://tr.im" via Java. Create the Java project "de.vogella.web.get" ...
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-download-file-url
Java Download File from URL | DigitalOcean
August 4, 2022 - It shows both ways to download file from URL in java. JavaDownloadFileFromURL.java · package com.journaldev.files; import java.io.BufferedInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; public class JavaDownloadFileFromURL { public static void main(String[] args) { String url = "https://www.journaldev.com/sitemap.xml"; try { downloadUsingNIO(url, "/Users/pankaj/sitemap.xml"); downloadUsingStream(url, "/Users/pankaj/sitemap_stream.xml"); } catch (IOException e) { e.pr
Find elsewhere
🌐
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 › https-example-com-download-files-https-java
How to Download Files from HTTPS URLs Using Java - CodingTechRoom
Downloading files from an HTTPS URL in Java involves the use of the `java.net.URL` and `java.net.HttpURLConnection` classes.
🌐
Matjazcerkvenik
matjazcerkvenik.si › developer › java-download-file-via-http.php
Java Download File via HTTP - Matjaž Cerkvenik
So all we need to do is call the same method in a loop until all the bytes from the server are transfered to our local disk. // url=http://www.example.com/testFile.zip // localFile=/path/to/testFile.zip public void download(String url, String localFile) throws Exception { System.out.printl...
🌐
amitph
amitph.com › home › java › how to download a file from url in java
How to Download a File from URL in Java - amitph
November 22, 2024 - HttpClient httpClient = ... Paths.get(outputPath));Code language: Java (java) First, we simply create an instance of HttpClient using its builder....
🌐
GitHub
gist.github.com › docsallover › 13dac15388a9d4e50f9aaa25a00f1151
Downloading Files From URL's In Java · GitHub
Clone via HTTPS Clone using the web URL. ... Clone this repository at <script src="https://gist.github.com/docsallover/13dac15388a9d4e50f9aaa25a00f1151.js"></script> Save docsallover/13dac15388a9d4e50f9aaa25a00f1151 to ...
🌐
Attacomsian
attacomsian.com › blog › java-download-save-file-from-internet
How to download and save a file from Internet in Java
December 11, 2019 - try (InputStream in = ... ex) { ex.printStackTrace(); } The Apache Commons IO library provides FileUtils.copyURLToFile() method to download and save a file from the Internet as shown below: try { // internet URL ...
🌐
Stack Overflow
stackoverflow.com › questions › 6266973 › how-to-enable-https-downloads-using-java
httpurlconnection - How to enable Https Downloads using java - Stack Overflow
public void run() { RandomAccessFile file=null; //download wiil be stored in this file InputStream in=null; //InputStream to read from try { HttpURLConnection conn=(HttpURLConnection)url.openConnection(); conn.setRequestProperty("Range","bytes="+downloaded+"-"); if(user!=null && pwd!=null){ String userPass=user+":"+pwd; String encoding = new sun.misc.BASE64Encoder().encode (userPass.getBytes()); conn.setRequestProperty ("Authorization", "Basic " + encoding); } conn.connect(); //..More code if(status==Status.CONNECTING) status=Status.DOWNLOADING; file=new RandomAccessFile(location,"rw"); file.s
🌐
GitHub
gist.github.com › madan712 › 8687784
Java program to download file from url · GitHub
Clone via HTTPS Clone using the web URL. ... Clone this repository at <script src="https://gist.github.com/madan712/8687784.js"></script> Save madan712/8687784 to your computer and use it in GitHub Desktop.
🌐
STechies
stechies.com › download-file-from-url-java
How to Download a File from a URL in Java
Within the try block, set the URL and the URLConnection using getInputStream(). The following catch block will handle any input-output exception and execute the printStackTrace(). The finally block (which executes automatically as a mandatory part of the program) will display the message “URL's File downloaded.” · Java NIO (abbreviated as New IO) is an alternative input-output Java API that also comes as a Java package.
🌐
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
🌐
Stack Abuse
stackabuse.com › how-to-download-a-file-from-a-url-in-java
How to Download a File from a URL in Java
August 21, 2018 - As you can see we open up a connection using the URL object and then read it via the BufferedInputStreamReader object. The contents are read as bytes and copied to a file in the local directory using the FileOutputStream. To lower the number of lines of code we can use the Files class available ...