Creating a Cookie Aware WebClient


 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 data
	String 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 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

 

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 class
cookies = ((CookieAwareWebClient)wc).CookieContainer; 
 
// now you can create new query with the cookies.
WebClient wc = new CookieAwareWebClient(cookies); (same as above);


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值