How to parse a cookie string

后端 未结 9 1878
眼角桃花
眼角桃花 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:06

    Funny enough, but java.net.HttpCookie class cannot parse cookie strings with domain and/or path parts that this exact java.net.HttpCookie class has converted to strings.

    For example:

    HttpCookie newCookie = new HttpCookie("cookieName", "cookieValue");
    newCookie.setDomain("cookieDomain.com");
    newCookie.setPath("/");
    

    As this class implements neither Serializable nor Parcelable, it's tempting to store cookies as strings. So you write something like:

    saveMyCookieAsString(newCookie.toString());
    

    This statement will save the cookie in the following format:

    cookieName="cookieValue";$Path="/";$Domain="cookiedomain.com"
    

    And then you want to restore this cookie, so you get the string:

    String cookieAsString = restoreMyCookieString();
    

    and try to parse it:

    List cookiesList = HttpCookie.parse(cookieAsString);
    StringBuilder myCookieAsStringNow = new StringBuilder();
    for(HttpCookie httpCookie: cookiesList) {
        myCookieAsStringNow.append(httpCookie.toString());
    }
    

    now myCookieAsStringNow.toString(); produces

    cookieName=cookieValue
    

    Domain and path parts are just gone. The reason: parse method is case sensitive to words like "domain" and "path".
    Possible workaround: provide another toString() method like:

    public static String httpCookieToString(HttpCookie httpCookie) {
        StringBuilder result = new StringBuilder()
                .append(httpCookie.getName())
                .append("=")
                .append("\"")
                .append(httpCookie.getValue())
                .append("\"");
    
        if(!TextUtils.isEmpty(httpCookie.getDomain())) {
            result.append("; domain=")
                    .append(httpCookie.getDomain());
        }
        if(!TextUtils.isEmpty(httpCookie.getPath())){
            result.append("; path=")
                    .append(httpCookie.getPath());
        }
    
        return result.toString();
    }
    

    I find it funny (especially, for classes like java.net.HttpCookie which are aimed to be used by a lot and lot of people) and I hope it will be useful for someone.

提交回复
热议问题