所以我正在对 HttpWebRequests 和 System.Net; 命名空间进行一些试验,我使用 POSTMAN 发出了一个 GET 请求,我得到了 3 个 cookie,现在我尝试用C# 但它似乎根本不返回任何 cookie。 或者它可能但可能是我以糟糕的方式做这件事。 执行 GET 请求和捕获 cookie 以便我以后可以将它们用于 POST 的正确方法是什么。
这就是我所拥有的。
似乎 cookieContainer
完成运行后为空,我也尝试调试。
public static void TestGET()
{
var request = (HttpWebRequest)WebRequest.Create("https://www.instagram.com/accounts/emailsignup/");
var cookieContainer = new CookieContainer();
using (var httpWebResponse = (HttpWebResponse)request.GetResponse())
{
using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
{
foreach (Cookie cookie in httpWebResponse.Cookies)
{
cookieContainer.Add(cookie);
}
}
}
}
最佳答案
您是在谈论响应 header 中的 3 个 Set-Cookies 值。如果是这样,下面的代码将得到那些。
如果您正在使用 HttpWebResponse(这就是您正在使用的)
using (var httpWebResponse = (HttpWebResponse)request.GetResponse())
{
var result = httpWebResponse.Headers["Set-Cookie"];
}
如果您使用的是 HttpResponseMessage:
if (httpResponse.Headers.TryGetValues("Set-Cookie", out values))
{
var session = values;
}
cookie 容器是空的,因为 httpWebResponse.Cookies 也是空的。
引用资料:
How to read HTTP header from response using .NET HttpWebRequest API?
How to get an specific header value from the HttpResponseMessage
关于c# - 为什么我的 GET 请求没有捕获任何 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48945750/