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:

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()

        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());


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.

Free Spring Boot Tutorial - 5 Hours Full Course

Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course