javax.ws.rs.core.Cookie vs javax.ws.rs.core.NewCookie ,有什么区别? [英] javax.ws.rs.core.Cookie vs javax.ws.rs.core.NewCookie , What is the difference?

查看:27
本文介绍了javax.ws.rs.core.Cookie vs javax.ws.rs.core.NewCookie ,有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 JAX-RS API javax.ws.rs.core.Cookiejavax.ws.rs.core.NewCookie 中找到了两个类.一个比另一个有什么优势?我想知道推荐使用哪一种以及何时使用?

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?

提前致谢:)

推荐答案

这不是关于推荐,而是关于合适.一种用于请求,一种用于响应.您可以看到两个不同的 javadoc.

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

表示在请求中传输的 HTTP cookie 的值.

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

NewCookie

用于创建新的 HTTP cookie,在响应中传输.

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

NewCookie,当在 Response 中发送时,将使用 cookie 设置一个 Set-Cookie response 标头信息,并且Cookie 将使用cookie 信息设置Cookie request 标头.这是根据 HTTP 规范.

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.

示例用法:

@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) {
    }
}

通常在客户端,您不会像我一样手动创建 Cookie.大多数情况下,您会从初始请求的响应中获取 cookie,然后将这些 cookie 发回.这意味着在 Response 中,您将拥有 NewCookies,您需要将它们转换为 Cookies 以供下一个请求使用.这可以通过调用 newCookie.toCookie()

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

这篇关于javax.ws.rs.core.Cookie vs javax.ws.rs.core.NewCookie ,有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆