Access the answers to your technology questions today.
Subscribe Now
30-day free trial. Register in 60 seconds.
What Makes Experts Exchange Unique?
Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.
Try it out and discover for yourself.
Subscribe Now
30-day free trial. Register in 60 seconds.
Join the Community
Give a Little. Get a Lot.
Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.
Join the Community
by: mariusoPosted on 2001-04-30 at 14:30:08ID: 6040774
Chances are, you know what key you are looking for. In particular, we want to capture any cookie that we get hit with. A header that asks our browser to store a cookie may look like this:Server=Netscape-Enter prise/3.6 SP2 ser_login_ session=b2 f897346a10 c683
session=b2 f897346a10 c683". To catch incoming cookies, we can ask for headers with a "Set-Cookie" key, usingString cookie = localConnection.getHeaderF ield("Set- Cookie");
; ookie",coo kie); // do this BEFORE getInputStream and BEFORE getHeader* !
Date=Tue, 26 Sep 2000 18:46:19 GMT
RequestStartSec=943323980
RequestStartUsec=334140
Set-Cookie=gx_session_id_U
Content-Type=text/html
Connection=close
Note the fifth header, which has a key of "Set-Cookie" and a value of "gx_session_id_User_login_
The resulting string will either be null (if no Set-Cookie header is present) or directly contain the cookie. Note that the cookie has itself a name and a value, divided by an "=". In addition to the actual cookie value, after a semicolon ":", there may be more data on the cookie such as an expiry date. In this case, the cookie string may for example look like this:sessauth=44c46a10; expires=Wednesday, 27-Sep-2000 03:59:59 GMT;
Most likely, you can ignore anything after the semicolon in your Java program. What you want to send back to the server when sending your next request to the same domain is just the cookie itself, in this case "sessauth=44c46a10". We can extract the actual cookie for example withint index = cookie.indexOf(";");
if(index >= 0) cookie = cookie.substring(0, index);Returning cookies
When getting the next page from this site (or another site in the same domain), you attach your newly received cookie to your request as follows:URLConnection conn = anotherURL.getConnection()
conn.setRequestProperty("C
Then you go on reading the body and possibly the header as above. You want to look for additional cookies and, more likely, Set-Cookie headers that change the value of your stored cookie. If the server sends you a cookie with the same name ("sessauth" in the example above), you simply overwrite your cookie with the new one.