开发者

Cannot get value from cookie in Java. Value contains commas.

开发者 https://www.devze.com 2022-12-19 09:39 出处:网络
I have problem with getting value from cookie that contains commas. It returns not full string but string cut off to first c开发者_高级运维omma. For example:

I have problem with getting value from cookie that contains commas. It returns not full string but string cut off to first c开发者_高级运维omma. For example:

// cookie value = var1,var2,var3
String cookieVal = cookie.getValue();
//cookieVal now is "var1" instead of "var1,var2,var3"

and

// cookie value = var1=var2=var3
String cookieVal = cookie.getValue();
//cookieVal now is "var1=var2=var3"

What am i doing wrong.


Take a look at the Cookie Documentation. It says :

This class supports both the Version 0 (by Netscape) and Version 1 (by RFC 2109) cookie specifications. By default, cookies are created using Version 0 to ensure the best interoperability.

And if you see the setValue method you will find this

With Version 0 cookies, values should not contain white space, brackets, parentheses, equals signs, commas, double quotes, slashes, question marks, at signs, colons, and semicolons. Empty values may not behave the same way on all browsers.

EDIT: Just read the google thing. Maybe try setting the version to 1 and see how it works.


The comma is part of the http-header value definition, so url-encode commas in your cookie value.

URLEncoder.encode(cookieValue);

I found this:

"This [cookie value] string is a sequence of characters excluding semi-colon, comma and white space. If there is a need to place such data in the name or value, some encoding method such as URL style %XX encoding is recommended, though no encoding is defined or required"

The RFC says:

Informally, the Set-Cookie response header comprises the token Set- Cookie:, followed by a comma-separated list of one or more cookies. Each cookie begins with a NAME=VALUE pair, followed by zero or more semi-colon-separated attribute-value pairs.

Update: After you clarified that you are parsing a cookie from google: I looked through all my __utmX cookies and none of them contains commas. The delimiter there is | or url-encoded :


Are you sure you need to store a set in the cookie? IMHO cookies should not be used to store data apart from identifiers. Data storage should be done on the server-side whenever possible.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号