HttpClient setHeader 和 addHeader 有什么区别?

HttpClient What is the difference between setHeader and addHeader?

使用 Apache HttpClient 版本时:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.6</version>
</dependency>

setHeader 和 addHeader 有什么区别?

    httpPost.addHeader("AuthenticationKey",authenticationKey);
    httpPost.addHeader("Content-Type","application/json");

    httpPost.setHeader("Cache-Control", "no-cache"); // HTTP 1.1
    httpPost.setHeader("Pragma", "no-cache"); // HTTP 1.0
    httpPost.setHeader("X-Requested-With", "XMLHttpRequest"); // mimics a browser REST request

addHeader: 添加一个 header 到这个消息。 header 将附加到列表的末尾。

setHeader:覆盖同名的第一个header。如果找不到具有给定名称的 header,新的 header 将附加到列表的末尾。

来自Javadoc

如果 header 的名称相同,

setHeader 方法覆盖 headers。但 addHeader 方法没有。它添加 headers 即使 header 的名字相同。

两种方法的签名信息如下:

**addHeader**
public void addHeader(String name,
                      String value)
Description copied from interface: HttpMessage
Adds a header to this message. The header will be appended to the end of the list.



**setHeader**
public void setHeader(String name,
                              String value)
Description copied from interface: HttpMessage
Overwrites the first header with the same name. The new header will be appended to the end of the list, if no header with the given name can be found.

从这些方法描述中,我们可以了解到 setHeader() 会用新的 header 信息替换现有的 header 数据,而 addHeader() 只是添加 header有名字。

您可以从文档中读到:

addHeader(String name, String value

Adds a header to this message. The header will be appended to the end of the list.

setHeader(String name, String value

Overwrites the first header with the same name. The new header will be appended to the end of the list, if no header with the given name can be found.