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?
openConnection(); Create a cookie string: String myCookie = "userId=igbrown"; Add the cookie to a request: Using the setRequestProperty(String name, String value); method, we will add a property named "Cookie", passing the cookie string created in the previous step as the property value.
To send cookies to the server, you need to add the "Cookie: name=value" header to your request. To send multiple Cookies in one cookie header, you can separate them with semicolons. In this Send Cookies example, we are sending HTTP cookies to the ReqBin echo URL.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With