HttpClient What is the difference between setHeader and addHeader?

Viewed 9110

When using Apache HttpClient version :

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

What is the difference between setHeader and 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
4 Answers

setHeader method override headers if header's names are same. But addHeader method doesn't. It adds headers even header's name are same.

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

setHeader: 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.

From Javadoc

Here is both method's signature information:

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

From these method descriptions, we can understand that setHeader() would replace the existing header data with new header information being given where as addHeader() simply adds the header with given name.

Related