Java,如何从字符串实例化 HttpCookie,有什么方便的方法吗?
我从 HTTP 响应标头中获取了一个 cookie 字符串,如下所示:
name=value; path=/; domain=.g.cn; expire=...
我可以将上面的行解析为键值对,而且,也可以轻松地将名称和值设置为 HttpCookie 实例,因为该对位于第一个。
但是如何设置其他对,因为我不知道哪个设置方法对应于下一个名称-值对的名称。遍历 cookie 可能包含的所有可能的键并调用匹配的设置方法,如下面的代码片段?
if (key.equalsIgnoreCase("path"))
cookie.setPath(value);
else if (key.equalsIgnoreCase("domain"))
cookie.setDomain(value);
太蠢了,有什么方便的方法吗? 提前致谢。
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 the 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
HttpCookie 提供了一个 parse(...) 方法来为您完成这项工作。查看 JavaDoc 在这里。如果这不是您想要的,那么请查看其方法的源代码。
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.
您可以使用
HashMap
然后只需迭代 cookie 字符串添加新的哈希条目,然后,完成后,您可以执行类似cookie.setPath(hash .get("path"))
和cookie.setDomain(hash.get("domain"))
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 likecookie.setPath(hash.get("path"))
andcookie.setDomain(hash.get("domain"))