【问题标题】:Why is my GET request not capturing any cookies?为什么我的 GET 请求没有捕获任何 cookie?
【发布时间】:2018-08-03 09:15:33
【问题描述】:

所以我在一般情况下对 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);
                    }
                }
            }
        }

【问题讨论】:

    标签: c# .net cookies httpwebrequest httpwebresponse


    【解决方案1】:

    您是在谈论响应标头中的 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

    【讨论】:

      猜你喜欢
      • 2017-01-16
      • 2014-01-24
      • 2017-04-26
      • 2016-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-30
      • 1970-01-01
      相关资源
      最近更新 更多