CookieContainer confusion

南笙酒味 提交于 2019-12-21 16:53:34

问题


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
}

then:

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

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?


回答1:


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();


来源:https://stackoverflow.com/questions/12024657/cookiecontainer-confusion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!