Saturday, February 19, 2011

Code is HttpClient or servlet API to parse Cookie header

Is there any existing code in Apache HttpClient or in the servlet API to parse Cookie header and obtain from a string that contains "name1=value1; name2=value2; ..." a list of Cookie? Writing code to parse this doesn't seem too hard, but if there is already some existing code, I'd like to use it.

From stackoverflow
  • If you call getCookies() on the HttpServletRequest object, it will return an array of Cookie objects. If you need to frequently look up cookies by name, then it may be easier to put them in to a Map so it's easy to look them up (rather than iterate over the Array each time). Something like this:

    public static Map<String,Cookie> getCookieMap(HttpServletRequest request) {
     Cookie[] cookies = request.getCookies();
     HashMap<String,Cookie> cookieMap = new HashMap<String,Cookie>();
     if (cookies != null) {
      for (Cookie cookie : cookies) {
       cookieMap.put(cookie.getName(), cookie);
      }
     }
     return cookieMap;
    }
    

    If you're using HttpClient and not servlets, you can get the Cookie array using:

    client.getState().getCookies()
    

    where client is your HttpClient object.

0 comments:

Post a Comment