How to send a cookie in a URLConnection?

筅森魡賤 提交于 2019-11-30 08:28:12

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/12761273/how-to-send-a-cookie-in-a-urlconnection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!