本文介绍了代码是HttpClient或servlet API来解析Cookie头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Apache HttpClient或servlet API中是否有任何现有代码来解析Cookie标头并从包含name1 = value1; name2 = value2; ...的字符串获取Cookie列表?编写代码解析这似乎太难了,但如果已经有一些现有的代码,我想使用它。

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.

推荐答案

如果您致电,它将返回一个 Cookie 对象的数组。如果您需要频繁地按名称查找Cookie,那么可能更容易将它们放入地图,以便查看它们(而不是每次迭代数组)。类似这样的:

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;
}



如果您使用HttpClient而不是servlet, c $ c> Cookie 数组使用:

client.getState().getCookies()

其中client是您的HttpClient对象。

where client is your HttpClient object.

这篇关于代码是HttpClient或servlet API来解析Cookie头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 01:02