Java: Adding additional HTTP request header with URLConnection

I have already shown you few HTTP operation using URLConnection class of java at my previous few postings. now I'm going to tell you how to add additional headers with your HTTP request.

First of all lets build a connection object, which we'll use at this post.

String url = "http://www.google.com/";
URLConnection urlConnection = new URL(url).openConnection();


Now we need to add a referer url with the urlConnection. The setRequestProperty() method of the URLConnection class is pretty useful for this kind of task.
urlConnection.setRequestProperty("referer", refererUrl);

Lets add an user agent with the request. People used to use lots of funny agent, we are considering our Opera as user agent.

urlConnection.setRequestProperty("user-agent", "Opera/9.0");

Do you want to add some cookie with your request header? It is also available for you.

urlConnection.setRequestProperty("cookie", "some_freaking_cookie_here");

Above three are the common headers that people used to add on request header. But its open to use more. For example to request GZip content, you can add below line of code.

urlConnection.setRequestProperty("Accept-Encoding", "gzip,deflate");

There are other headers like Accept-Charset, Accept-Language, Accept you can use too.

I have just shown you the way, its now upto you how you'll use it.

Thanks
Wolf.

Comments

Ranno said…
Hi, I saw your blog. Its nice. I would like to exchange links with your blog. If you are interested, then post a comment at http://javacodeonline.blogspot.com
Ashok Adsul said…
how to add session object to it..?