Search code examples
httpclientjava-11java-http-client

Explicitly setting `Content-Length` header in `java.net.http.HttpRequest`


I want to upload a file from InputStream over HTTP, and for this, I am using the new HttpClient provided as part of JDK11. When I try to set the Content-Length while creating a post request I get an IllegalArgumentException saying restricted header name: "Content-Length" and if I try to upload a file from InputStream without the Content-Length header I get an internal server error from the server where I want to upload the file. Is there any option to set the Content-Length in the request in Java 11? CodeI am using for creating HttpRequest:

var postRequest = HttpRequest.newBuilder()
                             .POST(HttpRequest.BodyPublishers.ofInputStream(() -> inputStream))
                             .uri(new URI(url))
                             .header(HttpHeaders.CONTENT_LENGTH, Long.toString(inputStreamSupplier.getFileSize()))
                             .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE)
                             .build();

Note: It won't be possible to update to Java 12 to allow the restricted headers.

I could also use another library, just wanted to know if there is an option to use the classes from JDK before switching to RestTemplate from Spring. (yes, it's deprecated, As the alternative uses spring boot can't use it at the moment)


Solution

  • Simply use fromPublisher:

    var bodyPublisher = BodyPublishers
        .fromPublisher(BodyPublishers.ofInputStream(()-> inputStream)), length);
    

    Note that you must ensure that the InputStream delivers exactly length bytes.