Skip to content

Instantly share code, notes, and snippets.

@wsky
Created July 28, 2012 07:25
Show Gist options
  • Save wsky/3192244 to your computer and use it in GitHub Desktop.
Save wsky/3192244 to your computer and use it in GitHub Desktop.
CookieAwareWebClient
/// <summary>
/// 支持cookie的webclient
/// <remarks>
/// 请求完成后会自动将响应cookie填充至CookieContainer
/// </remarks>
/// </summary>
internal class CookieAwareWebClient : WebClient
{
internal CookieContainer _cookieContainer = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address)
{
var request = base.GetWebRequest(address);
if (request is HttpWebRequest)
(request as HttpWebRequest).CookieContainer = this._cookieContainer;
return request;
}
protected override WebResponse GetWebResponse(WebRequest request)
{
var r = base.GetWebResponse(request);
if (r is HttpWebResponse)
this._cookieContainer.Add((r as HttpWebResponse).Cookies);
return r;
}
}
@wsky
Copy link
Author

wsky commented Jul 28, 2012

http://www.cnblogs.com/wsky/archive/2011/05/10/2042378.html

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并不是目标站点需要的,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment