19

My code is like the following:

URLConnection cnx = address.openConnection();
cnx.setAllowUserInteraction(false);         
cnx.setDoOutput(true);
cnx.addRequestProperty("User-Agent", 
    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
InputStream is = cnx.getInputStream();

Is it ok if I set the headers before I get the InputStream? Will my header be sent, or will the server see the default URLConnection's user-agent ( if any ) ?

sblundy
  • 60,628
  • 22
  • 121
  • 123
Geo
  • 93,257
  • 117
  • 344
  • 520

3 Answers3

21

The headers must be set prior to getting the InputStream to have any affect - an IllegalStateException will be thrown if the connection is already open.

As far as the User-Agent header specifically, it should be sent if it has been set.

See the URLConnection JavaDoc.

lowky12
  • 3
  • 2
Ken Gentle
  • 13,277
  • 2
  • 41
  • 49
4

To answer the question, the code is correct. The moment getInputStream(), an HTTP get is sent to the target server.

A side-note on user-agent, if you don't set it, URLConnection will send the default one anyway, which is:

User-Agent: Java/1.6.0_24 (varies depending on your java version)
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
Leif Ashley
  • 275
  • 1
  • 2
  • 13
-2

I'd advise against using low-level constructs such as URLConnection. There are plenty of libraries for sending HTTP requests, with the most prominent being Apache HTTP Client.

NewlessClubie
  • 983
  • 2
  • 8
  • 18