Saturday, August 15, 2009

Java: get all the cookies from http response header

If you are using URLConnection class from java, then below code will be helpful for you to extract the Set-Cookie header values from the HTTP response. The below function just return you the cookies from,

public String getCookies() throws Exception{
String headerName = null, returnCookie = "";

// creeating the url connection object
URL url = new URL("");
URLConnection urlConnection = url.openConnection();

// checking for each headers
for (int i=1; (headerName = urlConnection.getHeaderFieldKey(i))!=null; i++) {
// if its set-cookie, then take it
if (headerName.equalsIgnoreCase("Set-Cookie")) {
String cookie = urlConnection.getHeaderField(i);
returnCookie += cookie + "\n";
return returnCookie;

Actually this function will help you to find other HTTP headers. you'll just need to replace the Set-Cookie with your header. It can be content encoding, Location, etc.


1 comment:

Anonymous said...

really good

Get function name programaticaly - Python

This little piece of code will help you to get the function name programatically. This is very helpful when you are implementing the debug...