Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javax.ws.rs.core.Cookie vs javax.ws.rs.core.NewCookie , What is the difference?

I found two classes in JAX-RS API javax.ws.rs.core.Cookie and javax.ws.rs.core.NewCookie. What are the advantages of one over another? I would like to know Which one is recommended to use and when?

Thanks in advance :)

like image 552
Sagar Pudi Avatar asked Dec 02 '15 15:12

Sagar Pudi


1 Answers

It's not about recommended, it's about appropriate. One is for a request, and one is for a response. You can see the two different javadocs.

Cookie

Represents the value of a HTTP cookie, transferred in a request.

NewCookie

Used to create a new HTTP cookie, transferred in a response.

NewCookie, when sent in the Response, will set a Set-Cookie response header with the cookie information, and Cookie will set the Cookie request header with the cookie information. This is per the HTTP spec.

Example usage:

@GET
public Response get() {
    return Response.ok("blah")
            .cookie(new NewCookie("foo-cookie", "StAcKoVeRfLoW2020"))
            .build();
}

[..]

Client client = ClientBuilder.newClient();
Response response = client
        .target("https://cookieurl.com/api/some-resource")
        .request()
        .cookie(new Cookie("foo-cookie", "StAcKoVeRfLoW2020"))
        .get();

@Path("some-resource")
public class SomeResource {

    @POST
    public Response post(@CookieParam("foo-cookie") Cookie cookie) {
    }
}

Normally on the client side, you wouldn't manually create the Cookie as I did. Most of time you would get the cookies from the response of an initial request, then send those cookies back. This means that in the Response, you will have NewCookies and you you need to turn those into Cookies for the next request. This can easily be accomplished by calling newCookie.toCookie()

Map<String, NewCookie> cookies = response.getCookies();
Invocation.Builder ib = target.request();
for (NewCookie cookie: cookies.values()) {
    ib.cookie(cookie.toCookie());
}
Response response = ib.get();
like image 187
Paul Samsotha Avatar answered Oct 21 '22 07:10

Paul Samsotha