Java HttpClient to Download a Resource

In this source code example, we will write a source code to download a resource using Java 11 HttpClient API.

Java 11's standardization of HTTP client API that implements HTTP/2 and Web Socket. It aims to replace the legacy HttpUrlConnection class that has been present in the JDK since the very early years of Java.

Java HttpClient to Download a Resource

In this example, we will download the "javax.servlet-api-4.0.1.jar" file using HttpClient:
package com.springboot.blog.utils;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Path;

public class Main {

    public static void main(String[] args) throws IOException, InterruptedException {

        System.out.println("Downloading (please wait) ...");

        HttpClient client = HttpClient.newHttpClient();

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://repo1.maven.org/maven2/javax/servlet/javax.servlet-api/4.0.1/javax.servlet-api-4.0.1.jar"))
                .build();

        HttpResponse<Path> response = client.send(
                request, HttpResponse.BodyHandlers.ofFile(Path.of("javax.servlet-api-4.0.1.jar")));

        System.out.println("Status code: " + response.statusCode());
        System.out.println("\n Body: " + response.body());
    }
}

Output:

Downloading (please wait) ...
Status code: 200

 Body: javax.servlet-api-4.0.1.jar
Once you run the above Java program will download the file in your current folder.

In the above program, just change the URL to download any resource from the Internet.

Comments