我正在使用 WebClient 尝试访问网页。我必须先登录,然后网站设置 cookie。我正在使用这个问题 的代码 cookie 设置正确,但是当我尝试访问第二个页面时,我只是返回到登录页面。
private WebClientEx client;
public string GetFile(string URL)
{
Login();
// Download desired page
return client.DownloadString(URL);
}
private void Login()
{
using (client)
{
var values = new NameValueCollection
{
{ "Login", "xxxx" },
{ "Password", "xxxx" },
};
// Authenticate
client.UploadValues("http://www.xxxxxx.com/backoffice/login.php");
}
return;
}
}
/// <summary>
/// A custom WebClient featuring a cookie container
/// </summary>
public class WebClientEx : WebClient
{
public CookieContainer CookieContainer { get; private set; }
public WebClientEx()
{
CookieContainer = new CookieContainer();
}
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request.GetType() == typeof(HttpWebRequest))
((HttpWebRequest)request).CookieContainer = CookieContainer;
return request;
}
}