使用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(String name, String value
为此邮件添加标头。标题将附加到列表的末尾。
setHeader(String name, String value
覆盖具有相同名称的第一个标头。如果找不到具有给定名称的标头,则新标头将附加到列表的末尾。
如果标题的名称相同,setHeader
方法会覆盖标题。但addHeader
方法没有。它添加标题甚至标题的名称是相同的。
这是方法的签名信息:
**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()将替换现有的头数据,并给出新的头信息,其中addHeader()只是添加具有给定名称的头。