title: How to assign content-length header in Java 11+ HTTPClient
body: <p>I am trying to assign the content-length header in Java but it seems impossible.</p>
  <p>Here's my code:</p>
  <pre class="lang-java prettyprint-override"><code>        HttpRequest request = HttpRequest.newBuilder()
                  .uri(URI.create(&quot;URL&quot;))
                  .header(&quot;Content-Type&quot;,&quot;application/pdf&quot;)
                  .header(&quot;Authorization&quot;,String.format(&quot;Token token=%s&quot;,token))
                  .header(&quot;Transfer-Encoding&quot;,&quot;chunked&quot;)
                  .header(&quot;Content-Length&quot;,String.valueOf(contentLength))
                  .POST(HttpRequest.BodyPublishers.ofByteArray(file))
                  .build();
  </code></pre>
  <p>If I run this, then I get the exception &quot;Restricted Header Name: &quot;Content-Length&quot;. 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.</p>
  <p>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?</p>
  <p><strong>EDIT:</strong></p>
  <p>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.</p>