由于WebClient没有保存cookie的功能,需要包装下
private class CookieAwareWebClient : WebClient
{
public CookieAwareWebClient()
: this(new CookieContainer())
{ }
public CookieAwareWebClient(CookieContainer c)
{
this.CookieContainer = c;
}
public CookieContainer CookieContainer { get; set; }
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = this.CookieContainer;
}
return request;
}
}
使用例子如下:
CookieAwareWebClient
myWebClient = new(CookieContainer)
myWebClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
NameValueCollection myQueryStringCollection = new NameValueCollection();
myQueryStringCollection.Add("authenticity_token", Controller.HttpLoader.getToken());
myWebClient.QueryString = myQueryStringCollection;
myWebClient.UploadFileAsync(new Uri(uriString), "POST", "test.txt");
myWebClient.UploadFileCompleted += new UploadFileCompletedEventHandler(wc_UploadFileCompleted);