DEV Community

Pavel Polívka
Pavel Polívka

Posted on • Originally published at

Parsing cookie strings in Java with HttpCookie

The other day I was solving a very complex bug involving some sticky session cookies and multiple reverse proxies. During the bug solving process I discovered that I need to parse set-cookie header strings and do some value filtering in one of our reverse proxies.

My first idea was to write some kind of regex that would parse the string and get me my desired values. I went with something like this:

(.*?)=(.*?)($|;|,(?! ))
Enter fullscreen mode Exit fullscreen mode

Here is a regexer link.

Turns out this is more complex than simple regex. One string can contain multiple cookies, optional parameters, etc... Then there is an issue with multiple formats of how the cookie string can look like. I would need to write a lot of logic around my regex.

Naturally, I am a bit lazy so I started looking into what Java can offer. There must be an existing solution for this. I found a class named HttpCookie.

Usage is very simple:

List<HttpCookie> cookies = HttpCookie.parse(cookie);
Enter fullscreen mode Exit fullscreen mode

It will parse all the cookies in the string into a collection of objects that have all the needed info.

 private final String name; // NAME= ... "$Name" style is reserved
 private String value; // value of NAME

 // Attributes encoded in the header's cookie fields.
 private String comment; // Comment=VALUE ... describes cookie's use
 private String commentURL; // CommentURL="http URL" ... describes cookie's use
 private boolean toDiscard; // Discard ... discard cookie unconditionally
 private String domain; // Domain=VALUE ... domain that sees cookie
 private long maxAge = MAX_AGE_UNSPECIFIED; // Max-Age=VALUE ... cookies auto-expire
 private String path; // Path=VALUE ... URLs that see the cookie
 private String portlist; // Port[="portlist"] ... the port cookie may be returned to
 private boolean secure; // Secure ... e.g. use SSL
 private boolean httpOnly; // HttpOnly ... i.e. not accessible to scripts
 private int version = 1; // Version=1 ... RFC 2965 style
Enter fullscreen mode Exit fullscreen mode

This saved me a lot of time.

Top comments (0)