如何使用 WebClient 登录站点? [英] How do I log into a site with WebClient?
问题描述
我想使用 C# 中的 WebClient 对象下载某些内容,但下载域要求我登录.如何使用 WebClient 登录并保留会话数据?我知道如何使用 WebClient 发布数据.
I want to download something using a WebClient object in C#, but the download domain requires me to be logged in. How can I log in and keep session data using WebClient? I know how to post data with WebClient.
推荐答案
如果您遇到的问题是您可以进行身份验证但无法保留身份验证 cookie,这里是 WebClient 的 cookie 感知版本.
If the problem you are having is you can authenticate but you cant keep the authentication cookie here is a cookie aware version of WebClient.
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);
var castRequest = request as HttpWebRequest;
if (castRequest != null)
{
castRequest.CookieContainer = this.CookieContainer;
}
return request;
}
}
您给我的链接使用带有 HTTP POST 的表单身份验证,我没有时间仔细研究它,但至少它可以让您开始使用 Google.
The link you gave me uses forms authentication with HTTP POST, I don't have the time to walk though it but at least it gives you a start with Google.
这篇关于如何使用 WebClient 登录站点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!