Is there any existing code in Apache HttpClient or in the servlet API to parse Cookie header and obtain from a string that contains "name1=value1; name2=value2; ..." a list of Cookie? Writing code to parse this doesn't seem too hard, but if there is already some existing code, I'd like to use it.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
If you call getCookies() on the HttpServletRequest
object, it will return an array of Cookie
objects. If you need to frequently look up cookies by name, then it may be easier to put them in to a Map so it's easy to look them up (rather than iterate over the Array each time). Something like this:
public static Map<String,Cookie> getCookieMap(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
HashMap<String,Cookie> cookieMap = new HashMap<String,Cookie>();
if (cookies != null) {
for (Cookie cookie : cookies) {
cookieMap.put(cookie.getName(), cookie);
}
}
return cookieMap;
}
If you're using HttpClient and not servlets, you can get the Cookie
array using:
client.getState().getCookies()
where client is your HttpClient object.