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 :)
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 NewCookie
s and you you need to turn those into Cookie
s 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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With