Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 378
JavaSheriff Avatar asked Dec 02 '22 10:12

JavaSheriff


2 Answers

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.

like image 111
Wild_Owl Avatar answered Dec 04 '22 00:12

Wild_Owl


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

like image 27
Mustafa Çil Avatar answered Dec 03 '22 22:12

Mustafa Çil