Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign content-length header in Java 11+ HTTPClient

Tags:

java

http

I am trying to assign the content-length header in Java but it seems impossible.

Here's my code:

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("URL"))
                .header("Content-Type","application/pdf")
                .header("Authorization",String.format("Token token=%s",token))
                .header("Transfer-Encoding","chunked")
                .header("Content-Length",String.valueOf(contentLength))
                .POST(HttpRequest.BodyPublishers.ofByteArray(file))
                .build();

If I run this, then I get the exception "Restricted Header Name: "Content-Length". So then I remove the line where I set the content-length. At this point I get an IOException saying my request doesn't have a content-length header.

How the hell am I supposed to set the content-length header if the HttpClient throws an exception if I, you know, set the content length header?

EDIT:

I know this doesn't solve the question, but I ended up trying non-system standard HTTP Client Libaries. OkHttp for some reason failed on me, but Apache's HttpClient worked fine. It's not as elegant as Java's built in client, but it actually worked.

like image 543
Michael S Avatar asked Oct 29 '25 03:10

Michael S


1 Answers

HttpClient adds Content-Length header only for non-empty bodies. As you've noticed, overriding this header is restricted. Hopefully this can be relaxed since JDK 12 by setting a system property jdk.httpclient.allowRestrictedHeaders, see JDK-8213696.

like image 106
Jan Tosovsky Avatar answered Oct 30 '25 18:10

Jan Tosovsky