WebClient不能保持Session和Cookie,但很多情况下需要保持Session和Cookie,经过查看发现只要稍微修改一下就可以达到上述效果。
我实现了一个HttpWebClient,继承自WebClient,其代码如下:
Code
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;
}
}