Monday, May 07, 2007

Reading cookies from the server using Java

Last two posts have been about running TRACE on the host server.

Running TRACE on the server using Java from within the browser Part 1

Running TRACE on the server using Java from within the browser Part 2

In this post, we will see how to read all the HTTP headers including cookies. Tested on Firefox 2.0 and jdk 1.4

1. Get the browser host name from the location bar. Assuming the port is 80.
var l = "http://" + + "/";

2. Create a URL object to connect to the host.
var url = new;

3. Open the URL connection to the host.
var uc = url.openConnection();

4. Connect to the host.

5. Read all the headers returned from the server including the Cookies and display them as javascript alert.
var i = 1;
var header_keys;
while((header_keys = uc.getHeaderFieldKey(i))!= null) {
alert(header_keys + "=" + uc.getHeaderField(i));

6. Close the URL Connection

Run it as a bookmarklet
javascript:var l = "http://" + + "/";var url = new;var uc = url.openConnection();uc.connect();var i = 1;var header_keys;while((header_keys = uc.getHeaderFieldKey(i))!= null) {alert(header_keys + "=" + uc.getHeaderField(i));i++;}uc.close();

I am not sure if this will work for HttpOnly cookies but i would appreciate if someone could test this for HttpOnly cookies. I would be more then happy to walk them through, if they face any problems. You can reach me at anurag.agarwal__at__yahoo_dot_com

No comments: