URLConnection setRequestProperty vs addRequestProperty

user949300 picture user949300 · Jul 12, 2012 · Viewed 23.1k times · Source

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.

Answer

lambodar picture lambodar · Jul 28, 2014

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