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 google.com,


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

// creeating the url connection object
URL url = new URL("http://www.google.com");
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.

Thanks
Wolf

Comments

Anonymous said…
really good