Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload files using JDK 11 java.net.http.HttpClient?

Tags:

I recently encountered some problems with java.net.http.HttpClient that comes with JDK 11. I don't know how to use file upload. Found the ofInputStream() in java.net.http.BodyPublishers. I don't know if I using this method file upload. Here are the examples I wrote.

    public HttpResponse<String> post(String url, Supplier<? extends InputStream> streamSupplier, String... headers) throws IOException, InterruptedException {
        HttpRequest.Builder builder = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .headers(headers)
                .POST(null == streamSupplier ?
                        HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofInputStream(streamSupplier));
        HttpRequest request = builder.build();
        log.debug("Execute HttpClient Method:『{}』, Url:『{}』", request.method(), request.uri().toString());
        return client.send(request, HttpResponse.BodyHandlers.ofString());
    }
like image 384
Muscidae Avatar asked Nov 03 '19 07:11

Muscidae


1 Answers

The HttpRequest type provide factory method for creating request publisher for handling body type such as file:

HttpRequest.BodyPublishers::ofFile(Path)

You can update your method:

public HttpResponse<String> post(String url, Path file, String... headers) throws IOException, InterruptedException {
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .headers(headers)
            .POST(null == file ? HttpRequest.BodyPublishers.noBody() : 
                HttpRequest.BodyPublishers.ofFile(file))
            .build();

        log.debug("Execute HttpClient Method:『{}』, Url:『{}』", request.method(), 
            request.uri().toString());
        return client.send(request, HttpResponse.BodyHandlers.ofString());
}
like image 120
donquih0te Avatar answered Nov 15 '22 05:11

donquih0te