CookieContainer的困惑 [英] CookieContainer confusion

查看:82
本文介绍了CookieContainer的困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,CookieContainer通过HttpWebRequests持久化cookie的基本用法如下:

From what I understand, the basic use of the CookieContainer to persist cookies through HttpWebRequests is as follows:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
CookieContainer cookies = new CookieContainer();
request.CookieContainer = cookies;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
  // Do stuff with response
}

然后:

request = (HttpWebRequest)WebRequest.Create(new url);
request.CookieContainer = cookies;
etc...

但是我在理解此过程背后的逻辑时遇到了麻烦.变量cookie初始化后似乎没有在任何地方重新分配.来自第一个WebResponse的cookie如何准确地带入第二个WebRequest中?

But I'm having trouble understanding the logic behind this process. The variable cookies doesn't seem to have been reassigned anywhere after its initialization. How exactly do the cookies from the first WebResponse carry into the second WebRequest?

推荐答案

这是因为当您从网站检索响应时,它会自动填充用于请求的cookie容器.您可以通过查看响应前后存在哪些cookie来进行测试:

It's because when you retrieve the response from the website, it automatically populates the cookie container you used for the request. You can test this out by seeing what cookies are present before and after the response:

//Build the request
Uri site = new Uri("http://www.google.com");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(site);
CookieContainer cookies = new CookieContainer();
request.CookieContainer = cookies;

//Print out the number of cookies before the response (of course it will be blank)
Console.WriteLine(cookies.GetCookieHeader(site));

//Get the response and print out the cookies again
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    Console.WriteLine(cookies.GetCookieHeader(site));
}

Console.ReadKey();

这篇关于CookieContainer的困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆