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

后端 未结 1 2051
醉酒成梦
醉酒成梦 2020-12-19 00:44

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

相关标签:
1条回答
  • 2020-12-19 00:49

    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();
    
    0 讨论(0)
提交回复
热议问题