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