Vinoth
Vinoth

Reputation: 5785

Java http cookie

How can i get the cookie contents from a URL in java ?

Eg: Using LiveHttpHeaders when i visit google.com i can see cookie returned as follows.

Cookie: SID=DQAAAKEAAADA1VJiGC-O-Ml8cPfRIA8NxJ3rCQfXbRnh5NMw-l8eunfAKJNypj9Rss1_Ok2yyQXCU9qu4jM2TuASy2EE0KUknUOsdOgMz3W7WCDgey6OSZ-xi_ozh_lZP8paJ_OViG_G2FaTWciTyd4Mp_V0LYjgov1u6KkhATu8day8-nEckMXb4I56cse8SaiYFCjDmpUDmL6CDFij8Nxd3XDUEOTn5SCifKrRDohW6mAAaqzFPA; HSID=AvoV_TPUEmoSB6KMm; PREF=ID=260f8c0212fee1a7:U=6ca9509bc747fb21:TM=1297164689:LM=1297164690:S=opeCe3s85Xhm3Bq1; NID=43=EZNhkfgLmXVNQriZ2rjU0HGj6flDYy2nfsPD4Ef6pME0wvXxc5_avP1R9fSea0py_-F9xY3SJ6DpMvLXRT_bU7FH97s8sOmx7l49cwvNUbYTwJcY0xqs-0vKqybTeNZY

How do i get the value of SID ? These things are not available in getHeaderFieldKey() of UrlConnection class. I tried to get the default cookieHandler but the system returns null.

Upvotes: 1

Views: 2593

Answers (3)

jtahlborn
jtahlborn

Reputation: 53694

First you need to set the cookie handler before you connect to the url (e.g. CookieHandler.setDefault(new CookieManager())). then the cookies will be collected automagically and you can retrieve them from the CookieHandler if necessary.

Upvotes: 3

AlexR
AlexR

Reputation: 115328

Use request.getCookies() where request is of type HttpServletRequest. Request is passed to method doGet and/or doPost that your are expected to implement in servlet or JSP body if you are using JSP.

Upvotes: 0

ayush
ayush

Reputation: 14568

URL myUrl = new URL("http://www.hccp.org/cookieTest.jsp");
URLConnection urlConn = myUrl.openConnection();
urlConn.connect();

Since a server may set multiple cookies in a single request, we will need to loop through the response headers, looking for all headers named "Set-Cookie".

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

Extract cookie name and value from cookie string:

The string returned by the getHeaderField(int index) method is a series of name=value separated by semi-colons (;). The first name/value pairing is actual data string you are interested in (i.e. "sessionId=0949eeee22222rtg" or "userId=igbrown"), the subsequent name/value pairings are meta-information can be used to manage the storage of the cookie (when it expires, etc.).

 cookie = cookie.substring(0, cookie.indexOf(";"));
    String cookieName = cookie.substring(0, cookie.indexOf("="));
    String cookieValue = cookie.substring(cookie.indexOf("=") + 1, cookie.length());

Upvotes: 2

Related Questions