Thursday, September 6, 2012

Jersey Client: Using Cookies

Example code for how it's done:
// contains the cookies for the session
private Map<String,Cookie> cookies;

public String get(WebResource.Builder webResource) {
   // setting cookie before sending request
   Set<String> cookieNames = cookies.keySet();
   for(String cookieName : cookieNames){
       webResource = webResource.cookie(cookies.get(cookieName));
   }

   // send the request
   ClientResponse response = webResource.get(ClientResponse.class);

   // retrieving cookie from server response
   List<NewCookie> newCookies = response.getCookies();
   for (NewCookie newCookie : newCookies) {
       // new cookie replaces existing cookies with the same name
       cookies.put(newCookie.getName(),newCookie);
   }

   // do something with response
}

No comments:

Post a Comment