Generic Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

Java 11 officially introduced the Java HttpClient. Before that, we often used third-party libraries like Apache HttpClient when we needed to use an HTTP client.

In this short tutorial, we'll see how to add custom HTTP headers with the Java HttpClient.

2. Customize HTTP Headers

We can easily add custom headers using one of three methods from the HttpRequest.Builder object: header, headers, or setHeader. Let's see them in action.

2.1. Use header() Method

The header() method allows us to add one header at a time.

We can add the same header name as many times as we want, like in the example below, and they will all be sent:

HttpClient httpClient = HttpClient.newHttpClient();

HttpRequest request = HttpRequest.newBuilder()
  .header("X-Our-Header-1", "value1")
  .header("X-Our-Header-1", "value2")
  .header("X-Our-Header-2", "value2")
  .uri(new URI(url)).build();

return httpClient.send(request, HttpResponse.BodyHandlers.ofString());

2.2. Use headers() Method

If we want to add multiple headers at the same time, we can use the headers() method:

HttpRequest request = HttpRequest.newBuilder()
  .headers("X-Our-Header-1", "value1", "X-Our-Header-2", "value2")
  .uri(new URI(url)).build();

This method also allows us to add multiple values to one header name:

HttpRequest request = HttpRequest.newBuilder()
  .headers("X-Our-Header-1", "value1", "X-Our-Header-1", "value2")
  .uri(new URI(url)).build();

2.3. Use setHeader() Method

Finally, we can use the setHeader() method to add a header. But, unlike the header() method, if we use the same header name more than once, it will overwrite any previous header(s) that we had set with that name:

HttpRequest request = HttpRequest.newBuilder()
  .setHeader("X-Our-Header-1", "value1")
  .setHeader("X-Our-Header-1", "value2")
  .uri(new URI(url)).build();

In the example above, the value of our header will be “value2”.

3. Conclusion

In summary, we've learned different ways to add custom HTTP headers with the Java HttpClient.

As always, the example code from this article is available over on GitHub.

Generic bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE
Generic footer banner
guest
0 Comments
Inline Feedbacks
View all comments