简体   繁体   中英

How do I get a Cookie with an invalid character (colon ":") in the cookie name in Java?

First of all, I can't change the cookie name. I would encode it if I had control over it. I don't know how they could add a cookie with invalid chars in the first place.

I'm hitting this endpoint say www.abc.com/test and it returns a cookie header like

the::cookie::name=the::cookie::value

I was able to retrieve the cookie in both Postman and in frontend using Javascript.

I want to get this cookie in Java code. I tried using below Java code.

Is there a workaround for this? thanks in advance!

CookieManager cm = new CookieManager();
CookieHandler.setDefault(cookieManager);

URL url = new URL("www.abc.com/test");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
...
...
con.getHeaderField("Set-Cookie"); // returns empty String


List<HttpCookie> cookies = cm.getCookieStore().getCookies(); // empty list

No errors. The cookie just gets ignored.

Your best bet is likely to implement your own CookieHandler instead of using the default CookieManager :

CookieManager cm = new MyCookieManager();
CookieHandler.setDefault(cookieManager);

In MyCookieManager.put() you then do your own parsing of the HTTP response headers for finding those non standard cookies:

class MyCookieManager implements CookieHandler {
    @Override
    public void put(URI uri, Map<String, List<String>> responseHeaders) throws IOException {
        // Manually parse the response headers
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM