代码之家  ›  专栏  ›  技术社区  ›  JavaSheriff

HttpClient setHeader和addHeader有什么区别?

  •  -1
  • JavaSheriff  · 技术社区  · 6 年前

    使用Apache HttpClient版本时:

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

        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 回复  |  直到 6 年前
        1
  •  11
  •   Wild_Owl    6 年前

    从文档中可以看到:

    addHeader(String name, String value

    setHeader(String name, String value

    用相同的名称覆盖第一个标头。如果找不到具有给定名称的标题,则新标题将附加到列表的末尾。

        2
  •  4
  •   Mustafa Çil    6 年前

    setHeader addHeader 方法没有。即使标题的名称相同,它也会添加标题。

        3
  •  1
  •   user10527814 user10527814    6 年前

    添加标题

    :用相同的名称覆盖第一个标头。如果找不到具有给定名称的标题,则新标题将附加到列表的末尾。

    Javadoc

        4
  •  1
  •   Udaya Shankara Gandhi Thalabat    6 年前

    以下是两个方法的签名信息:

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