javagoogle-apigoogle-http-client

Set-Cookie with Google HTTP Client Library for Java


I just started using the Google HTTP Client Library for Java and I like it a lot. However, I don't know if there's an easy way to handle the case when a server sends header Set-Cookie. I looked through documentation, sample code, and Javadoc and saw nothing, so I started implementing my own solution. However, this process seems common enough that I would think Google would have implemented a solution for everyone.

Server sends something like:

Set-Cookie: uid=ef308bd9-4580-4ef0-8cdd-2b09f383419e; Expires=Tue, 31 Dec 2199 23:59:59 GMT; Domain=mydomain.com; Path=/

My client has to manually parse it all:

String[] parts = cookie.split(";");
if (parts.length > 0) {
    Pattern p = Pattern.compile("([^\\s=]*)=(.*)");
    Matcher m = p.matcher(parts[0]);
    if (m.matches()) {
        Cookie cookie = new Cookie(m.group(1), m.group(2));
        if (parts.length > 1) {
            for (int i = 1; i < parts.length; i++) {
                // parse and set "Expires", "Max-Age", "Domain", "Path",
                // "Secure", "HttpOnly", etc.
            }
        }
    }
}

Is there any library method to handle this stuff instead of me implementing it myself?


Solution

  • To parse cookies use

    java.net.HttpCookie.parse(String header)
    

    Still need to store parsed cookies and send them with Cookie header. There are plenty solutions for cookie handling over internet though it's odd that Google doesn't provide it with their library.