Saturday, August 15, 2009

Java: Adding additional HTTP request header with URLConnection

Share at Facebook

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 = "";
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.



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

ashok said...

how to add session object to it..?

Alita Duplanty said...

I had very felt the interest for your blogamazing videos,