Setting request headers

The HttpRequest.Builder class uses three methods to set additional headers:

  • header​(String name, String value) and setHeader​(String name, String value): These are used to add headers one by one, as shown in the following code:
HttpRequest request = HttpRequest.newBuilder()
.uri(...)
...
.header("key_1", "value_1")
.header("key_2", "value_2")
...
.build();

HttpRequest request = HttpRequest.newBuilder()
.uri(...)
...
.setHeader("key_1", "value_1")
.setHeader("key_2", "value_2")
...
.build();
The difference between header() and setHeader() is that the former adds the specified header while the latter sets the specified header. In other words, header() adds the given value to the list of values for that name/key, while setHeader() overwrites any previously set values for that name/key.
  • headers​(String... headers): This is used to add headers separated by a comma, as shown in the following code:
HttpRequest request = HttpRequest.newBuilder()
.uri(...)
...
.headers("key_1", "value_1", "key_2",
"value_2", "key_3", "value_3", ...)
...
.build();

For example, the Content-Type: application/json and Referer: https://reqres.in/ headers can be added to the request that's triggered by the https://reqres.in/api/users/2 URI, as follows:

HttpRequest request = HttpRequest.newBuilder()
.header("Content-Type", "application/json")
.header("Referer", "https://reqres.in/")
.uri(URI.create("https://reqres.in/api/users/2"))
.build();

You can also do the following:

HttpRequest request = HttpRequest.newBuilder()
.setHeader("Content-Type", "application/json")
.setHeader("Referer", "https://reqres.in/")
.uri(URI.create("https://reqres.in/api/users/2"))
.build();

Finally, you can do something like this:

HttpRequest request = HttpRequest.newBuilder()
.headers("Content-Type", "application/json",
"Referer", "https://reqres.in/")
.uri(URI.create("https://reqres.in/api/users/2"))
.build();

Depending on the goal, all three methods can be combined in order to specify the request headers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.81.33