How to Download a file over HTTP

Share This Post

In general, downloading a file from an HTTP server terminal via HTTP GET consists of the following steps:

  • Make an HTTP GET request to send to the HTTP server.
  • Send an HTTP request and receive an HTTP response from the HTTP server.
  • Save the contents of the HTTP response file to a local file.

Java codes to download a file from an HTTP server endpoint via HTTP GET

With that in mind, let’s change the code for how to send an HTTP GET request in Java and store the file contents of the HTTP response in a local file.


import java.io.IOException;

import java.io.FileOutputStream;

import java.net.HttpURLConnection;

import java.net.URL;

import java.nio.channels.Channels;

import java.nio.channels.FileChannel;

import java.nio.channels.ReadableByteChannel;

public class HttpGetDownloadFileExample {

    public static void main(String[] args) {

        ReadableByteChannel readableChannelForHttpResponseBody = null;

        FileChannel fileChannelForDownloadedFile = null;

        try {

            // Define server endpoint

            URL robotsUrl = new URL("http://www.techcoil.com/robots.txt");

            HttpURLConnection urlConnection = (HttpURLConnection) robotsUrl.openConnection();

            // Get a readable channel from url connection

            readableChannelForHttpResponseBody = Channels.newChannel(urlConnection.getInputStream());

            // Create the file channel to save the file

            FileOutputStream fosForDownloadedFile = new FileOutputStream("robots.txt");

            fileChannelForDownloadedFile = fosForDownloadedFile.getChannel();

 

            // Save the body of the HTTP response to local file

            fileChannelForDownloadedFile.transferFrom(readableChannelForHttpResponseBody, 0, Long.MAX_VALUE);

 

        } catch (IOException ioException) {

            System.out.println("IOException occurred while contacting server.");

        } finally {

 

            if (readableChannelForHttpResponseBody != null) {

 

                try {

                    readableChannelForHttpResponseBody.close();

                } catch (IOException ioe) {

                    System.out.println("Error while closing response body channel");

                }

            }

 

            if (fileChannelForDownloadedFile != null) {

 

                try {

                    fileChannelForDownloadedFile.close();

                } catch (IOException ioe) {

                    System.out.println("Error while closing file channel for downloaded file");

                }

            }

 

        }

    }

}

Download a file over HTTP

As shown above, I created the class using the main method. When the main method is executed, the Java application does a few things.

  • First, I declared the ReadableByteChannel and FileChannel instances to contain null values ​​to make them easier to block.
  • Once that’s done, define a test block to execute the file download logic that can throw controlled exceptions.
  • Within the test block, first, use the URL instance to get an HttpURLConnection instance that points to the HTTP server endpoint for the file you want to download.
  • Once that is done, you will get a sample ReadableByteChannel mapped to the URL connection input stream. Also, set it in the readable ChannelForHttpResponseBody variable for later manipulation.
  • After getting an instance of ReadableByteChannel, continue to get a FileChannel that points to the local file path where you want to save the downloaded file. In this case, save the downloaded file as robots.txt in the same directory where you run your Java application.
  • Finally, use the readable ChannelForHttpResponseBody’s fileChannelForDownloadedFile.transfer from the method to save the body content of the HTTP response to a local file.

Downloading a file from an HTTP server endpoint via HTTP POST

The client may need to provide certain information to the HTTP server to download the file. In these situations, HTTP POST is a better HTTP method for downloading files.

To download a file from an HTTP server via HTTP POST, similar to HTTP GET:

  • Make an HTTP POST request to send to the HTTP server.
  • Send an HTTP request and receive an HTTP response from the HTTP server.
  • Save the contents of the HTTP response file to a local file.

Read More: How to Validate Phone Number Using PHP?

Reasons to Download a file over HTTP

There are a few reasons why you might want to download a file over HTTP instead of HTTPS.

One reason is that HTTP is often faster than HTTPS. This is because the encryption process used by HTTPS can add some latency to the transaction.

Another reason is that some websites (like YouTube) do not allow users to download videos over HTTPS. If you try to download a video over HTTPS, you will get an error message telling you that the video cannot be downloaded in that format. In these cases, it’s usually easier to just download the video over HTTP.

Finally, there are some situations where it’s not possible to use HTTPS. For example, if you’re using a public Wi-Fi network and the network.

spot_img

Related Posts

Python for Loop Iteration: How to Easily Manipulate a List

One of the most powerful features of the Python...

How To Get First Characters of a String in Python

Way to find the first characters of a string...

How To Convert Tuple To String In Python

In this post, you will learn how to convert...

How To Convert String to Double in Python

Good to hear, that you want to convert a...

Python TypeError: String Index Out Of Range Solution

A string is an array of characters and part...

How To Remove Empty Strings From a List Of Strings

On this page, we will discuss how to remove...
- Advertisement -spot_img