anuj dhiman anuj dhiman - 5 months ago 79
Java Question

How to get cookie in filter rest api jersey

I am send cookie from client in rest api request and i want to read on filter. I am using this code on filter for retrive cookies .

Map<String, Cookie> cookies = requestContext.getCookies();
Cookie cookie = cookies.get("token");
String token = cookie.getValue();


But it return null. Can anyone suggest me how can i retrive cookie on filter.

Answer

In order to retrieve your cookie, you should do the following:

for (Cookie c : requestContext.getCookies().values()) 
{
    if (c.getName().equals("token")) {
        cookie = c;
        break;
    }
}

Honestly, I don't know why you could not retrieve your cookie by its key, since the ContainerRequestContext documentation states that getCookies returns a read-only map of cookie name (String) to Cookie.