Creating a Cookie Aware WebClient

来源:互联网 发布:iphone电池保养 知乎 编辑:程序博客网 时间:2024/06/15 15:54


 C# has an object called WebClient that makes it easier to execute POSTs and GETs. But is doesn't handle the cookie.

the follow class handle the cookies:

 

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;    }    public 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;    }    public override WebResponse GetWebResponse(WebRequest request)    {         WebResponse response = base.GetWebResponse(request); //this string contains the cookies dataString setCookieHeader = response.Headers[HttpResponseHeader.SetCookie];if (setCookieHeader != null){    ////do something if needed to parse out the cookie.// NOTE: the cookies from the request is handled by the response itself, don't need add again.// if you want to create your cookie, do the following.    //if (setCookieHeader != null)    //{        Cookie cookie = new Cookie(); //create cookiethis.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

 

How to use:

1. use cookie. CookieContainer cookies = new CookieContainer ();WebClient wc = new CookieAwareWebClient(cookies);wc.Encoding = Encoding.UTF8; // send request, the class will get the cookies from the response and store the cookies in its CookieContainer (property);string data = wc.UploadString(uri, postStr);  // or = wc.DownloadString(uri);// get the cookies from classcookies = ((CookieAwareWebClient)wc).CookieContainer;  // now you can create new query with the cookies.WebClient wc = new CookieAwareWebClient(cookies); (same as above);


 

 

原创粉丝点击