gpt4 book ai didi

c# - 使用 Cookie 感知 WebClient

转载 作者:行者123 更新时间:2023-11-30 17:43:20 27 4
gpt4 key购买 nike

我正在使用 this enhanced version of WebClient登录网站:

public class CookieAwareWebClient : WebClient
{
public CookieAwareWebClient()
{
CookieContainer = new CookieContainer();
}
public CookieContainer CookieContainer { get; private set; }

protected override WebRequest GetWebRequest(Uri address)
{
var request = (HttpWebRequest)base.GetWebRequest(address);
request.CookieContainer = CookieContainer;
return request;
}
}

这样我就可以将 cookie 发送到网站:

using (var client = new CookieAwareWebClient())
{
var values = new NameValueCollection
{
{ "username", "john" },
{ "password", "secret" },
};
client.UploadValues("http://example.com//dl27929", values);

// If the previous call succeeded we now have a valid authentication cookie
// so we could download the protected page
string result = client.DownloadString("http://domain.loc/testpage.aspx");
}

但是当我运行我的程序并捕获 Fiddler 中的流量时,我得到 302 状态代码。我用这种方式在 Fiddler 中测试了请求,一切正常,我得到了 200 的状态码。
Fiddler中的请求:

GET http://example.com//dl27929 HTTP/1.1
Cookie: username=john; password=secret;
Host: domain.loc

这是应用程序发送的请求:

POST http://example.com//dl27929 HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: www.domain.loc
Content-Length: 75
Expect: 100-continue
Connection: Keep-Alive

如您所见,它不会发送 cookie。
有什么想法吗?

最佳答案

一切正常,只是我忘了设置 cookie,谢谢 Scott :

client.CookieContainer.SetCookies(new Uri("http://example.com//dl27929"), "username=john; password=secret;");

关于c# - 使用 Cookie 感知 WebClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31129578/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com