【问题标题】:Getting Cookie value from MessageContext.HTTP_RESPONSE_HEADERS从 MessageContext.HTTP_RESPONSE_HEADERS 获取 Cookie 值
【发布时间】:2013-01-25 17:31:11
【问题描述】:

如何从 cookie 列表中获取特定 cookie 的值。以下是我的尝试:

        Map<String, List<String>> map = (Map<String, 
                List<String>>) context.get(MessageContext.HTTP_RESPONSE_HEADERS);

        List<String> contentType = getHTTPHeader(map);
        if (contentType != null) {
            StringBuffer strBuf = new StringBuffer();
            for (String type : contentType) {
                strBuf.append(type);
            }
            System.out.println("Content-Type:" + strBuf.toString());
        }

        List<String> cookies = map.get("Set-Cookie"); 
        if (cookies != null) {
            System.out.println("cookies != null");
            StringBuffer strBuf = new StringBuffer();
            for (String type : cookies) {
                System.out.println(" Looping cookie ");
                strBuf.append(type);
            }
            System.out.println("Cookie:" + strBuf.toString());
        }else{
            System.out.println("cookies == null");
        }

我得到以下结果,我想获得“JSESSIONID”的价值

Cookie:JSESSIONID=88E53DE2E78TRE86E1C2B021BA240B; Path=/us-webservice

谢谢。

【问题讨论】:

  • 不能从会话本身获取会话ID吗?
  • 什么意思?它已被设置为 cookie 的一部分,我必须在下一个请求中读取并传递它。
  • 如果您发出请求,像 httpclient 这样的客户端可以自动为您处理这些 cookie。

标签: java cookies http-headers


【解决方案1】:

cookie.substring(cookie.indexOf(':'), cookie.indexOf(';')).split("=")[1]

或者如果你想要正则表达式

Pattern p = Pattern.compile( "JSESSIONID=([A-Z0-9]+)");
Matcher m = p.matcher(cookie);
m.find();
m.group(1);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-24
    • 1970-01-01
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    相关资源
    最近更新 更多