2014-07-01 194 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"進一步擴大:

發送者必須不產生在消息中使用相同的字段 名稱的多個報頭字段,除非任何爲該 頭字段整個字段值被定義作爲逗號分隔的列表[即,#(值)] 或頭部字段是衆所周知的例外(如下所述)。

接收者可以與相同的場 名稱組合多個報頭字段爲一個「字段名:字段值」對,在不改變消息的 語義,通過附加每個後續字段值 組合字段值按順序排列,用逗號分隔。訂單 其中收到的字段名稱相同的字段字段是 ,因此重要的是對組合字段 的解釋值;當 轉發消息時,代理不得更改這些字段值的順序。