E Paiz
E Paiz

Reputation: 681

How to send a cookie in a URLConnection?

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?

Upvotes: 15

Views: 36664

Answers (2)

eis
eis

Reputation: 53462

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).

Upvotes: 31

Edwin Dalorzo
Edwin Dalorzo

Reputation: 78579

Well, if you are only setting a cookie I guess you could simply do like:

urlConn.setRequestProperty("Cookie", "user=mary17; domain=airtravelbargains.com; path=/autos");

If you're setting more than one cookie than you could probably use the addRequestProperty method instead.

For the expires attribute make sure to use the format: Weekday, DD-Mon-YY HH:MM:SS GMT.

The only legal time zone is GMT, and the separators between the elements of the date must be dashes.

Upvotes: 9

Related Questions