Handeling session cookies with Java

Let’s say you are creating an HTTP request using Java.

You are probably doing it with the use of the URL object like this:

			URL u = new URL("http://www.google.com/");
			URLConnection uc = u.openConnection();
			uc.connect();

But sometimes you will also want to use cookies to send along with you request.

To do so first we will learn how to read cookies from the request.

Getting the cookies from a URL connection
After the function uc.connect(); you are able to get cookies from your request.

			URL u = new URL("http://www.google.com/");
			URLConnection uc = u.openConnection();
			uc.connect();

			String headerName=null;
			for (int i=1; (headerName = uc.getHeaderFieldKey(i))!=null; i++) {
			 	if (headerName.equals("Set-Cookie")) {                  
				String cookie = uc.getHeaderField(i);  
				System.out.println(cookie);
			 	}
			 }

Here is the result of this example:

PREF=ID=f0fd8b4c16931772:TM=1261387922:LM=1261387922:S=LLhLkHSpgfXkqxIe; expires=Wed, 21-Dec-2011 09:32:02 GMT; path=/; domain=.google.co.uk
NID=30=C6Hb5SV2-pqYymnnrZmTAprCvDMrFwo6wzg9We7rvPztXmA_fTWxv-GPmDVXPsIBOOkecj1Ms4skmTWT-uUN5iW_-ZYiPUNNJXE8CC44xWVORe8Yyu1jI32XL51tvzCz; expires=Tue, 22-Jun-2010 09:32:02 GMT; path=/; domain=.google.co.uk; HttpOnly

Sending HTTP request with cookies:

			URL u = new URL("http://www.google.com/");
			URLConnection uc = u.openConnection();
			uc.setRequestProperty("Cookie", "name1=value1; name2=value2");
			uc.connect();

Notice that the value of the property ‘Cookie’ is a string which contains cookies in the format of cookieName=CookieValue with a ‘;’ as a delimiter.

Notice you have to set the cookie value before the connect() function.

downloaddownload source

Leave a Reply

Your email address will not be published.