WebClient保持Session和Cookie
WebClient不能保持Session和Cookie,但很多情况下需要保持Session和Cookie,经过查看发现只要稍微修改一下就可以达到上述效果。
我实现了一个HttpWebClient,继承自WebClient,其代码如下:
namespace System.Net
{
public class HttpWebClient : WebClient
{
private CookieContainer cookies;
public HttpWebClient()
{
this.cookies = new CookieContainer();
}
public HttpWebClient(CookieContainer cookies)
{
this.cookies = cookies;
}
public CookieContainer Cookies
{
get
{
return this.cookies;
}
set
{
this.cookies = value;
}
}
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
HttpWebRequest httpRequest = request as HttpWebRequest;
httpRequest.CookieContainer = cookies;
}
return request;
}
}
本文基于署名 2.5 中国大陆许可协议发布,欢迎转载,演绎或用于商业目的,但是必须保留本文的署名小橋流水(包含链接)。如您有任何疑问或者授权方面的协商,请给我发邮件。