Search code examples
javaapache-commons-httpclient

HttpClient What is the difference between setHeader and addHeader?


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

Solution

  • As you can read from documentation:

    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.