1

我正在发送请求,但 cookie 没有存储在我的容器中以进行响应?

代码示例 -

        string uri = "https://www.localhost.com/"
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
        request.ContentType = "application/x-www-form-urlencoded";
        CookieContainer cookies = new CookieContainer();
        request.CookieContainer = cookies;
        System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;


        using (Stream stream = request.GetRequestStream())
        {
            byte[] bytes = new UTF8Encoding().GetBytes(s);
            stream.Write(bytes, 0, bytes.Length);
        }


        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            using (Stream stream2 = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(stream2, Encoding.UTF8))
                    {
                        str6 = reader.ReadToEnd();
                    }
                }
        }

如您所见,我已经实施

  CookieContainer cookies = new CookieContainer();
  request.CookieContainer = cookies;

哪个应该将来自请求的 cookie 存储在容器中,以便在响应权中进一步使用?就像响应需要请求 cookie 来加载页面一样。

4

1 回答 1

0

我建议使用 HttpClient,因为它会为您处理 cookie,而且通常更易于使用。另请注意,即使它是一次性的,您通常也应该在整个应用程序中使用相同的 HttpClient。请参阅:https ://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/

于 2018-08-02T01:57:36.827 回答