在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。