How can I put a cookie in Jersey RESTful webservice?

只愿长相守 提交于 2019-12-07 19:28:26

问题


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

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.

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

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.

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


回答1:


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.

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



来源:https://stackoverflow.com/questions/9684103/how-can-i-put-a-cookie-in-jersey-restful-webservice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!