Java 如何在 Jersey RESTful webservice 中放置 cookie?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9684103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:07:02  来源:igfitidea点击:

How can I put a cookie in Jersey RESTful webservice?

javarestsessioncookiesjersey

提问by Junseok Oh

I would like to put a cookie from "PUT webservice result" to "POST webservice" by Jersey API.

我想通过 Jersey API 将“PUT webservice result”中的 cookie 放入“POST webservice”。

Here is my code

这是我的代码

WebResource service1 = client.resource("http://test.com");

ClientResponse logResponse = service1.accept(MediaType.APPLICATION_XML).put(ClientResponse.class, "<?xml version='1.0'?><test>1</test>");

WebResource service2 = client.resource("http://test.com/post");
WebResource.Builder builder = service2.getRequestBuilder();

for(Cookie c : logResponse.getCookies())
{
if(c.getName().equals("SESSID"))
    builder = builder.cookie(c);
}

ClientResponse test = builder.accept(MediaType.TEXT_XML).post(ClientResponse.class, "<?xml version='1.0'?><post>abc</post>");

I thought If I set a cookie by "Builder.cookie" method, the cookie value will be added on the header of request for POST web service.

我想如果我通过“Builder.cookie”方法设置了一个cookie,cookie值将被添加到POST Web服务请求的头部。

So, in this case, the cookie from the PUT web service will be set into POST web service.

因此,在这种情况下,来自 PUT Web 服务的 cookie 将被设置为 POST Web 服务。

However, if I check the header(by logResponse.getHeaders()and test.getHeaders()methods) after two web services, first PUT web service has the Cookie but second POST web service does not have any cookies.

但是,如果我在两个 Web 服务之后检查标头(通过logResponse.getHeaders()test.getHeaders()方法),第一个 PUT Web 服务有 Cookie,但第二个 POST Web 服务没有任何 cookie。

Anybody can help me to keep a cookie between two web services?

任何人都可以帮助我在两个 Web 服务之间保留 cookie?

回答by Martin Matula

The server sets the cookie only once (i.e. only the first response has Set-Cookie header). Once the client gets the cookie, it should attach it to it's requests, but the server no longer sends the cookie in the responses. That's normal behavior. So not sure what problem you are trying to solve.

服务器只设置 cookie 一次(即只有第一个响应具有 Set-Cookie 标头)。一旦客户端获得 cookie,它应该将它附加到它的请求中,但服务器不再在响应中发送 cookie。这是正常的行为。所以不确定你要解决什么问题。

Here is how you can write a Jersey filter that will make sure it adds the cookies set by the server to every request: Jersey Client: Adding Cookies to Request

以下是编写 Jersey 过滤器的方法,以确保它将服务器设置的 cookie 添加到每个请求中:Jersey 客户端:向请求添加 cookie