title: How to add headers based on multiple conditions to HttpRequest Java 11?
body: <p>I'm learning the <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/package-summary.html" rel="nofollow noreferrer">java.net.http api</a>, trying to download a file given a range of bytes already downloaded. For this the <code>range</code> header can be used (supposing the server supports such feature).</p>
  
  <p>Using <code>org.apache.http.client.methods.HttpGet</code> I can do this:</p>
  
  <pre><code>HttpGet httpGet= new HttpGet("http://exampleURL.com/aFile");
  if (myFile.length() &gt; 0) {
              httpGet.addHeader("Range", "bytes=" + myFile.length() + "-"+totalBytes));
  }
  httpGet.addHeader("xxxx", "yyyy");//ok
  </code></pre>
  
  <p>Now with HttpRequest I can't add new headers dynamically, I have to create a new whole HttpRequest:</p>
  
  <pre><code>HttpRequest request = null;
  if (myFile.length() &gt; 0) {
    request = HttpRequest.newBuilder()
        .uri(URI.create("http://exampleURL.com/aFile"))
        .header("Range","bytes="+myFile.length() +"-"+ totalBytes)
        .build();
  }else{
    request = HttpRequest.newBuilder()
        .uri(URI.create("http://exampleURL.com/aFile"))
        .build();
  }
  request.header("xxxx","yyyyy")//Can't do this anymore
  </code></pre>
  
  <p>I there a way add them dynamically?</p>
  
  <p>I see that the docs say:</p>
  
  <blockquote>
    <p>Once built an HttpRequest is immutable, and can be sent multiple times.</p>
  </blockquote>
  
  <p>But what's the point to be immutable? What if I need for any reason to modify the headers?</p>
  
  <p>Reference:</p>
  
  <p><a href="https://openjdk.java.net/groups/net/httpclient/intro.html" rel="nofollow noreferrer">https://openjdk.java.net/groups/net/httpclient/intro.html</a></p>