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

最后修改: 2022年 6月 8日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

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

2.自定义HTTP头信息

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

2.1.使用header()方法

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

2.2.使用headers()方法

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

如果我们想同时添加多个头文件,我们可以使用headers()方法。

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

2.3.使用setHeader()方法

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:

最后,我们可以使用setHeader()方法来添加一个头。但是,与header()方法不同的是,如果我们多次使用同一个头的名称,它将覆盖我们以前用该名称设置的任何头

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

3.总结

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.

一如既往,本文中的示例代码可在GitHub上获得