How can I put a cookie in Jersey RESTful webservice?

13,534

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

Share:
13,534
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    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?