开发者

Java, How to Instance HttpCookie from a String, any convenient ways?

I have got a cookie string from HTTP response header like the following line:

name=value; path=/; domain=.g.cn; expire=...

I can parse the above line to key-value pairs, and, also it's easy to set the name and value to HttpCookie instance as this pair comes the first.

But how to set the other pairs since I don't know which set-method corresponds to the name of th开发者_如何转开发e next name-value pair. Traverse all possible keys a cookie may contian and call the matched set-method, like below snippet?

if (key.equalsIgnoreCase("path"))
 cookie.setPath(value);
else if (key.equalsIgnoreCase("domain"))
 cookie.setDomain(value);

That's foolish, any convenient ways? Thanks in advance.


HttpCookie provides a parse(...) method that does the work for you. Look at the JavaDoc here. If this is not what you want then look at the source code of its method.


You could use a HashMap<String, String> then just iterate through the cookie string adding new hash entries, then, once you're done, you can do something like cookie.setPath(hash.get("path")) and cookie.setDomain(hash.get("domain"))

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜