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();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…