Creating a Cookie Aware WebClient

posted by Bryan on

C# has an object called WebClient that makes it easier to execute POSTs and GETs. However, if you ever have to deal with managing cookies, the WebClient doesn't do this out of the box, which puzzles me. It's not too hard to implement though.

Consider this class:

public class CookieAwareWebClient : WebClient
{
    public CookieContainer CookieContainer { get; set; }
    public Uri Uri { get; set; }

    public CookieAwareWebClient() : this (new CookieContainer())
    {
    }

    public CookieAwareWebClient(CookieContainer cookies)
    {
        this.CookieContainer = cookies;
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);
        if (request is HttpWebRequest)
  {
       (request as HttpWebRequest).CookieContainer = this.CookieContainer;
  }
  HttpWebRequest httpRequest = (HttpWebRequest) request;
  httpRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
  return httpRequest;
    }

    protected override WebResponse GetWebResponse(WebRequest request)
    {
        WebResponse response = base.GetWebResponse(request);
  String setCookieHeader = response.Headers[HttpResponseHeader.SetCookie];

  if (setCookieHeader != null)
  {
      //do something if needed to parse out the cookie.
      if (setCookieHeader != null)
      {
          Cookie cookie = new Cookie(); //create cookie
    this.CookieContainer.Add(cookie);
      }
  }
  return response;
    }
}

You will see two overridden methods for GetWebRequest and GetWebResponse. These methods can be overridden to handle the cookie container. You will also notice the AutomaticDecompression that can be placed on the HttpWebRequest to validate the response is being unzipped (GZIP) automatically since the WebClient doesn't do this out of the box.

Now, when calling web services or executing POSTs or GETs, it will handle holding your cookies for you automatically. They are included in subsequent requests.

Props go to my hero Tyler.

Share the delectableness

About Bryan Robinson

Bryan has worked in software development since 2007. He spent about 5 years as QA and focused primarily on automation. Experience includes .NET and Java automation tools. Currently, Bryan is a mobile web developer working in Riverton Utah. He is married to a beautiful wife and they have 3 kids. More by Bryan

Leave a comment

blog comments powered by Disqus