Syntax highlighter header

Thursday, 24 August 2023

Using new HttpClient API for downloading file

Recently we were required to download a CSV file from our partner website in our Java application. So I explored new Java HttpClient API. The APIs are asynchronous which is good for scalability but confusing for the users. After struggling for a long time I was able to figure out how to download the file which was protected by a username and password. 

The code for downloading file is provided below, it also include a call to get just headers using HEAD call.

import java.io.IOException;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class HttpClientMainClass {
    public static void main(String[] args) throws URISyntaxException, IOException, InterruptedException {
        HttpClient httpClient = HttpClient.newBuilder().authenticator(new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication("username","password".toCharArray());
                    }
                })
                .build();

        HttpRequest httpRequest2 = HttpRequest.newBuilder().method("HEAD", HttpRequest.BodyPublishers.noBody())
                .uri(new URI("http://example.com/data.csv"))
                .build();
        HttpResponse<Void> resp2 = httpClient.send(httpRequest2,
                HttpResponse.BodyHandlers.discarding());

        System.out.println(resp2);
        System.out.println(resp2.headers());

        HttpRequest httpRequest = HttpRequest.newBuilder().GET()
                .uri(new URI("http://example.com/data.csv"))
                .build();
        HttpResponse<Path> resp = httpClient.send(httpRequest,
                HttpResponse.BodyHandlers.ofFile(Path.of("/tmp","data.csv"),
                        StandardOpenOption.CREATE, StandardOpenOption.WRITE));

        if(resp.statusCode()==200) {
            System.out.println("File downloaded At : "+resp.body());
        }
    }
}

Hope it will be useful for the readers.

Ref: https://www.baeldung.com/java-9-http-client

No comments:

Post a Comment