How to parse a cookie string

后端 未结 9 1874
眼角桃花
眼角桃花 2020-12-08 04:47

I would like to take a Cookie string (as it might be returned in a Set-Cookie header) and be able to easily modify parts of it, specifically the expiration date.

I s

9条回答
  •  旧巷少年郎
    2020-12-08 05:08

    The advantage of Yanchenko's approach with Apache Http client is that is validates the cookies consistent with the spec based on the origin. The regular expression approach won't do that, but perhaps you don't need to.

    public class CookieUtil {
    
        public List parseCookieString(String cookies) {
            List cookieList = new ArrayList();
            Pattern cookiePattern = Pattern.compile("([^=]+)=([^\\;]*);?\\s?");
            Matcher matcher = cookiePattern.matcher(cookies);
            while (matcher.find()) {
                int groupCount = matcher.groupCount();
                System.out.println("matched: " + matcher.group(0));
                for (int groupIndex = 0; groupIndex <= groupCount; ++groupIndex) {
                    System.out.println("group[" + groupIndex + "]=" + matcher.group(groupIndex));
                }
                String cookieKey = matcher.group(1);
                String cookieValue = matcher.group(2);
                Cookie cookie = new BasicClientCookie(cookieKey, cookieValue);
                cookieList.add(cookie);
            }
            return cookieList;
        }
    }
    

    I've attached a small example using yanchenkos regex. It needs to be tweaked just a little. Without the '?' quantity modifer on the trailing ';' the trailing attribute for any cookie will not be matched. After that, if you care about the other attributes you can use Doug's code, properly encapsulated, to parse the other match groups.

    Edit: Also, note '*' qualifier on the value of the cookie itself. Values are optional and you can get cookies like "de=", i.e. no value at all. Looking at the regex again, I don't think it will handle the secure and discard cookie attributes which do not have an '='.

提交回复
热议问题