为WebClient增加Cookie支持
时间:2011-05-10 来源:wsky
System.Net.WebClient是.net提供的高级api,使用上很便捷,但是默认的实现缺乏对cookie的支持,比如您希望使用它来进行模拟登录时,无法直接获取响应的cookie(它没有直接提供操作方法),google了一下,也发现了很简易的改进,如:
http://couldbedone.blogspot.com/2007/08/webclient-handling-cookies.html
http://codehelp.smartdev.eu/2009/05/08/improve-webclient-by-adding-useragent-and-cookies-to-your-requests/
就是重写GetWebRequest(Uri address)即可,不过实际场景这样可不够用,比如你要模拟登录的地址并非是要访问的目标地址时,比如登录过程有302重定向之类的,上述文章中的实现都会使得您携带的cookie并不是目标站点需要的,
那么我们来对它再做一下改进,既然重写了GetWebRequest,不如把GetWebResponse也重写一下吧:
1: /// <summary>
2: /// 支持cookie的webclient
3: /// <remarks>
4: /// 请求完成后会自动将响应cookie填充至CookieContainer
5: /// </remarks>
6: /// </summary>
7: internal class CookieAwareWebClient : WebClient
8: {
9: internal CookieContainer _cookieContainer = new CookieContainer();
10:
11: protected override WebRequest GetWebRequest(Uri address)
12: {
13: var request = base.GetWebRequest(address);
14: if (request is HttpWebRequest)
15: (request as HttpWebRequest).CookieContainer = this._cookieContainer;
16: return request;
17: }
18: protected override WebResponse GetWebResponse(WebRequest request)
19: {
20: var r = base.GetWebResponse(request);
21: if (r is HttpWebResponse)
22: this._cookieContainer.Add((r as HttpWebResponse).Cookies);
23: return r;
24: }
25: }
上述便是完整代码:)
相关阅读 更多 +