Custom HTTP Header With the Java HttpClient – 用Java HttpClient自定义HTTP头

最后修改: 2022年 6月 8日

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.

Java 11正式引入了Java HttpClient>。在此之前,当我们需要使用 HTTP 客户端时,我们经常使用第三方库,如Apache HttpClient

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

在这个简短的教程中,我们将看到如何用Java HttpClient添加自定义的HTTP头信息。

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.

我们可以使用HttpRequest.Builder对象中的三个方法之一,轻松地添加自定义头文件。header, headers, 或setHeader。让我们看看它们的作用。

2.1. Use header() Method


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

header() 方法允许我们一次添加一个头。

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”.

在上面的例子中,我们的头的值将是 “value2″。

3. Conclusion


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

综上所述,我们已经学会了用Java HttpClient添加自定义HTTP头的不同方法。

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