18

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.

user949300
  • 15,364
  • 7
  • 35
  • 66

2 Answers2

19

The basic difference between setRequestProperty and addRequestProperty is:-

  1. setRequestProperty>> Sets the general request property. If a property with the key already exists, overwrite its value with the new value.

  2. addRequestProperty >> Adds a general request property specified by a key-value pair. This method will not overwrite existing values associated with the same key.

For more information browse the api doc

lambodar
  • 3,495
  • 5
  • 34
  • 58
7

The first code snippet would result in two accept-headers while the second code snippet would give one accept-header with two selectors.

They are in fact equivalent.

The spec also states that the more specific media range have precedence, so both would yield your expected behavior.

If you must specify several media ranges, and they are equally specific, you could add the q-parameter.

Source: http 1.1 spec ( http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html ) :

jtahlborn
  • 52,909
  • 5
  • 76
  • 118
Nils Otto
  • 611
  • 6
  • 16
  • Thanks. Somehow I thought that the order mattered for preference, but, reading the docs, I see that it doesn't. What if the media types are equally specific, e.g. application/xml and application/json. Does order matter or do you need to use q values to set a preference? – user949300 Jul 12 '12 at 19:46