据我了解,基本采用的CookieContainer的坚持饼干通过HttpWebRequests如下:
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...
但我无法理解这个过程背后的逻辑。 变量饼干似乎并没有被它的初始化后的任何地方重新分配。 从第一WebResponse的饼干究竟如何带入第二的WebRequest?
这是因为当您检索从网站的响应,它会自动填充时使用的请求的cookie的容器。 你可以看到的饼干都存在前后响应后测试了这一点:
//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();