Search code examples
javahttp-headershttprequestjava-11java-http-client

How to add headers based on multiple conditions to HttpRequest Java 11?


I'm learning the java.net.http api, trying to download a file given a range of bytes already downloaded. For this the range header can be used (supposing the server supports such feature).

Using org.apache.http.client.methods.HttpGet I can do this:

HttpGet httpGet= new HttpGet("http://exampleURL.com/aFile");
if (myFile.length() > 0) {
            httpGet.addHeader("Range", "bytes=" + myFile.length() + "-"+totalBytes));
}
httpGet.addHeader("xxxx", "yyyy");//ok

Now with HttpRequest I can't add new headers dynamically, I have to create a new whole HttpRequest:

HttpRequest request = null;
if (myFile.length() > 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

I there a way add them dynamically?

I see that the docs say:

Once built an HttpRequest is immutable, and can be sent multiple times.

But what's the point to be immutable? What if I need for any reason to modify the headers?

Reference:

https://openjdk.java.net/groups/net/httpclient/intro.html


Solution

  • As Albjenow suggested you can create the builder with common fields first and then build the final request after applying your logic. It would look like :

    HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
                    .uri(URI.create("http://exampleURL.com/aFile"));
    
    if (myFile.length() > 0) {
        requestBuilder.header("Range","bytes="+myFile.length() +"-"+ totalBytes);
    }
    
    requestBuilder.header("xxxx","yyyyy");
    
    HttpRequest request = requestBuilder.build();