Home » How to Download a file over HTTP?

How to Download a file over HTTP?

  • by
Download a file over HTTP

Last Updated on November 2, 2021 by admin

In general, downloading a file from an HTTP server terminal via HTTP GET consists of the following these 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?

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *