Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

java - 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 :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...