所以我试图在 ASP.NET 页面中使用 WebClient 登录 Pinterest。这是我目前使用的 CookieWebAwareClient:
public class CookieAwareWebClient : WebClient
{
public CookieAwareWebClient()
: this(new CookieContainer())
{ }
public CookieAwareWebClient(CookieContainer c)
{
this.CookieContainer = c;
this.Headers.Add("User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5");
}
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;
}
}
这是我用来登录的代码,首先执行 GET 请求以获取 csrf 令牌和他们使用的其他 _ch 值。
var client = new CookieAwareWebClient();
client.Encoding = Encoding.UTF8;
string html = client.DownloadString("https://pinterest.com/login/");
string csrftoken = GetCSRFToken(html);
string chtoken = GetCHToken(html);
var values = new NameValueCollection();
values.Add("email", HttpUtility.UrlEncode(MY_EMAIL));
values.Add("password",MY_PASSWORD);
values.Add("csrfmiddlewaretoken", csrftoken);
values.Add("_ch", chtoken);
// 403 Error happens below
client.UploadValues("https://pinterest.com/login/?next=%2Flogin%2F", values);
html = client.DownloadString("http://pinterest.com/settings");
我觉得我只是错过了一些小东西,但无法确定它是什么。