17

Lets say I'm talking HTTP to a web server, and I will Accept html or text, but prefer html. In other words, the header should say (I think!)

Accept: text/html, text/*

I'm using Java, so I have a URLConnection. Should I use:

myUrlConnction.setRequestProperty("Accept", "text/html");
myUrlConnction.addRequestProperty("Accept", "text/*");

or

myUrlConnction.setRequestProperty("Accept", "text/html, text/*");

or are they equivalent???

In general, most of the third party code I see doesn't seem to worry much about ordering or multiple values of these headers, so I'm wondering how it ends up working.

4

2 回答 2

19

setRequestProperty 和 addRequestProperty 之间的基本区别是:-

  1. setRequestProperty>>设置一般请求属性。如果具有键的属性已存在,则用新值覆盖其值。

  2. addRequestProperty >>添加由键值对指定的通用请求属性。此方法不会覆盖与同一键关联的现有值。

有关更多信息,请浏览api 文档

于 2014-07-28T09:54:02.870 回答
7

第一个代码片段将产生两个接受标头,而第二个代码片段将提供一个带有两个选择器的接受标头。

它们实际上是等价的。

该规范还指出,更具体的媒体范围具有优先权,因此两者都会产生您预期的行为。

如果您必须指定多个媒体范围,并且它们同样具体,您可以添加 q 参数。

来源:http 1.1 规范(http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html):

于 2012-07-12T19:32:00.893 回答