在C#中,使用HttpWebRequest
類處理Cookies的方法如下:
CookieContainer
對(duì)象,用于存儲(chǔ)服務(wù)器返回的Cookies。CookieContainer cookieContainer = new CookieContainer();
CookieContainer
對(duì)象分配給HttpWebRequest
對(duì)象的CookieContainer
屬性。HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://example.com");
request.CookieContainer = cookieContainer;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// 處理響應(yīng)
}
response.Cookies
集合獲取服務(wù)器返回的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
對(duì)象分配給新的HttpWebRequest
對(duì)象的CookieContainer
屬性。HttpWebRequest secondRequest = (HttpWebRequest)WebRequest.Create("https://example.com/otherpage");
secondRequest.CookieContainer = cookieContainer;
通過以上步驟,您可以在C#中使用HttpWebRequest
類處理Cookies。