0

Is there a nice way to pass cookie to all request that use same Client object?
Right now I must pass cookie to every request like this:

final Client client = ClientBuilder.newClient(clientConfig);
UriBuilder authenticate_url = UriBuilder.fromUri("xxxxxxxxx/authenticate");

WebTarget webTarget = client.target(authenticate_url);
Invocation.Builder invocationBuilder =  webTarget.request(MediaType.APPLICATION_XML);
Response response = invocationBuilder.get();


Map<String, NewCookie> cookies = response.getCookies(); //store cookies

webTarget = client.target(other_url);       
invocationBuilder =  webTarget.request(MediaType.APPLICATION_XML).cookie(cookies.get("KEY"));

response = invocationBuilder.get(); //works

invocationBuilder =  webTarget.request(MediaType.APPLICATION_XML);

response = invocationBuilder.get(); //does not work
Tirmean
  • 398
  • 7
  • 18
  • 1
    [Use a ClientRequestFilter](https://jersey.github.io/documentation/latest/filters-and-interceptors.html). I think the cookie map un the ClientRequestContext might be unmodifiable though. You might need to just set the `Cookie` header manually. – Paul Samsotha Aug 10 '17 at 11:28
  • As an aside, the cookie map from the response returns `NewCookie`s. This is only from server to client. Client to server should use `Cookie`. You can turn a `NewCookie` to a `Cookie` by calling `newCookie.toCookie()`. https://stackoverflow.com/q/34046292/2587435 – Paul Samsotha Aug 10 '17 at 11:39

1 Answers1

0

Either you can use @Context like this

@GET
public String get(@Context HttpHeaders hh) 
{

MultivaluedMap<String, String> headerParams = hh.getRequestHeaders();
    Map<String, Cookie> pathParams = hh.getCookies(); 
}

or you can use @CookieParam annotation like so

@POST
public void post(@CookieParam("<parmeter name>") CookieParameter ckparameter) {

    ...
}

UPDATE

In your invocation Builder add

invocationBuilder.header("Cookie", "example-cookie=hello world;exapmle2-cookie=hai all");
harsha kumar Reddy
  • 1,251
  • 1
  • 20
  • 32