代码是HttpClient或servlet API来解析Cookie头

发布于 2024-07-11 00:48:31 字数 154 浏览 5 评论 0原文

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

赠我空喜 2024-07-18 00:48:31

如果您调用 getCookies() HttpServletRequest 对象上,它将返回一个 Cookie 对象数组。 如果您需要经常按名称查找 cookie,那么将它们放入 Map 中可能会更容易,这样就可以轻松查找它们(而不是每次都迭代数组)。 像这样的事情:

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,则可以使用以下方法获取 Cookie 数组:

client.getState().getCookies()

其中 client 是您的 HttpClient 对象。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文