2014-07-01 195 views
0

在JAVA HttpURLConnection类,的请求报头的设置的主要逻辑代码如下:HTTP标题密钥可以重复吗?

public synchronized void set(String k, String v) { 
     for (int i = nkeys; --i >= 0;) 
      if (k.equalsIgnoreCase(keys[i])) { 
       values[i] = v; 
       return; 
      } 
     add(k, v); 
} 

据验证了键应该是唯一的,所述钥匙具有保持与值一对一的映射关系。

相反,在HeaderFields of Response模块中,结构被定义为Entry>。也就是说,密钥不会与该值保持一对一的映射关系。

这是为什么? HTTP协议是否有相关的协议?

添加: 在HttpClient4,请求报头的设置的主要逻辑代码如下:响应的

/** 
* Replaces the first occurence of the header with the same name. If no header with 
* the same name is found the given header is added to the end of the list. 
* 
* @param header the new header that should replace the first header with the same 
* name if present in the list. 
*/ 
public void updateHeader(final Header header) { 
    if (header == null) { 
     return; 
    } 
    // HTTPCORE-361 : we don't use the for-each syntax, i.e. 
    //  for (Header header : headers) 
    // as that creates an Iterator that needs to be garbage-collected 
    for (int i = 0; i < this.headers.size(); i++) { 
     final Header current = this.headers.get(i); 
     if (current.getName().equalsIgnoreCase(header.getName())) { 
      this.headers.set(i, header); 
      return; 
     } 
    } 
    this.headers.add(header); 
} 

部首

/** 
* Gets all of the headers with the given name. The returned array 
* maintains the relative order in which the headers were added. 
* 
* <p>Header name comparison is case insensitive. 
* 
* @param name the name of the header(s) to get 
* 
* @return an array of length >= 0 
*/ 
public Header[] getHeaders(final String name) { 
    final List<Header> headersFound = new ArrayList<Header>(); 
    // HTTPCORE-361 : we don't use the for-each syntax, i.e. 
    //  for (Header header : headers) 
    // as that creates an Iterator that needs to be garbage-collected 
    for (int i = 0; i < this.headers.size(); i++) { 
     final Header header = this.headers.get(i); 
     if (header.getName().equalsIgnoreCase(name)) { 
      headersFound.add(header); 
     } 
    } 

    return headersFound.toArray(new Header[headersFound.size()]); 
} 

它们是同HttpURLConnection类的

回答

2

HTTP协议是否有相关的协议?

是。 RFC 2616 Section 4.2 "Message Headers"说:

多幅具有相同字段名的消息头域可以 存在于消息当且仅当该 头字段整个字段值被定义为逗号分隔的列表[即#(值)]。 必须可以将多个报头字段组合成一个 “字段名称:字段值”对,而不改变 消息的语义,方法是将每个后续字段值附加到第一个,每个 之间用一个逗号。因此,接收字段名称相同的字段字段的顺序对于组合字段值的解释有重要意义,因此代理不得在转发消息时更改这些字段值的顺序。

这是通过RFC 7230 Section 3.2.2 "Field Order"进一步扩大:

发送者必须不产生在消息中使用相同的字段 名称的多个报头字段,除非任何为该 头字段整个字段值被定义作为逗号分隔的列表[即,#(值)] 或头部字段是众所周知的例外(如下所述)。

接收者可以与相同的场 名称组合多个报头字段为一个“字段名:字段值”对,在不改变消息的 语义,通过附加每个后续字段值 组合字段值按顺序排列,用逗号分隔。订单 其中收到的字段名称相同的字段字段是 ,因此重要的是对组合字段 的解释值;当 转发消息时,代理不得更改这些字段值的顺序。