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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With