DEV Community

Pavel Polívka
Pavel Polívka

Posted on • Originally published at ppolivka.com

3 1

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.

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay