取一个网站上的软件,发现对方为了防采集将下载地址进行ID变化,这样就需要webclient在下次请求时保持上次请求的Session和cookie才行,继承WebClient写了个类,就可以了。
/// <summary>
/// HttpClient 的摘要说明
/// </summary>
public class HttpClient:WebClient
{
private CookieContainer cookieContainer;
public HttpClient()
{
//
// TODO: 在此处添加构造函数逻辑
//
this.cookieContainer = new CookieContainer();
}
/**/
/// <summary>
/// 创建一个新的 WebClient 实例。
/// </summary>
/// <param name="cookie">Cookie 容器</param>
public HttpClient(CookieContainer cookies)
{
this.cookieContainer = cookies;
}
/**//// <summary>
/// Cookie 容器
/// </summary>
public CookieContainer Cookies
{
get { return this.cookieContainer; }
set { this.cookieContainer = value; }
}
/**//// <summary>
/// 返回带有 Cookie 的 HttpWebRequest。
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
HttpWebRequest httpRequest = request as HttpWebRequest;
httpRequest.CookieContainer = cookieContainer;
}
return request;
}
}