在C#中,使用HttpWebRequest
类处理Cookies的方法如下:
CookieContainer
对象,用于存储服务器返回的Cookies。CookieContainer cookieContainer = new CookieContainer();
CookieContainer
对象分配给HttpWebRequest
对象的CookieContainer
属性。HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://example.com");
request.CookieContainer = cookieContainer;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// 处理响应
}
response.Cookies
集合获取服务器返回的Cookies。if (response.Cookies.Count > 0)
{
foreach (Cookie cookie in response.Cookies)
{
Console.WriteLine("Name: " + cookie.Name);
Console.WriteLine("Value: " + cookie.Value);
Console.WriteLine("Domain: " + cookie.Domain);
Console.WriteLine("Path: " + cookie.Path);
Console.WriteLine("Expires: " + cookie.Expires);
}
}
CookieContainer
对象分配给新的HttpWebRequest
对象的CookieContainer
属性。HttpWebRequest secondRequest = (HttpWebRequest)WebRequest.Create("https://example.com/otherpage");
secondRequest.CookieContainer = cookieContainer;
通过以上步骤,您可以在C#中使用HttpWebRequest
类处理Cookies。