How to send a cookie in a URLConnection?

E Paiz picture E Paiz · Oct 6, 2012 · Viewed 28.1k times · Source

What is the proper way to send a 'full' cookie across a URLConnection?

I've been using:

URL url = new URL(page);  
URLConnection urlConn = url.openConnection(); 

urlConn.setRequestProperty("Cookie", myCookie); 

urlConn.setUseCaches(true); 

urlConn.connect();

The myCookie value is testCookie=d1lEZk9rSHd3WnpBd2JkWGRhN1RYdz09OkEwQ21pSFJVZzBpVDhhUENaK3ZPV2c9PQ

Is there a way to send the Path,Domain, and Expires with it? Do you need to encode the value in some way?

Answer

eis picture eis · Nov 23, 2014

This (currently accepted) answer is wrong - for http clients you use ; separator for multiple cookie values, so his example actually sends three coookies:

  • user=mary17
  • domain=airtravelbargains.com
  • path=/autos

If we were talking about a server response and Set-Cookie header, the answer would be right, but we're not - urlconnection is for client connecting to server.

So what about the Domain, Expires, Path information then that you asked for? The thing is, you're not meant to send that information. Path, Domain and Expires are only instructions that are meant to be sent to the browser (or any other HTTP client), as they're instructions for the client. You're only meant to send the valid cookie values to the server, so there is no way to send the information you asked for because it would not make any sense.

You can see this yourself by browsing any HTTP session you have in your browser. Browser will only send stuff like this:

Cookie: cookiename=value; anothercookie=othervalue;

Which is as it is supposed to be.

Or, you can inspect RFC 6265, where you can see directly from the table of contents that Domain, Expires, Path are attributes of the Set-Cookie header (sent to the browser), not of Cookie header (sent by the browser or other http client to the server).