利用 HttpClient 取得 Cookie
雖然標題寫的是 HttpClient,但實際上取得 Cookie 是透過 HttpClientHandler 裡的 CookieContainer 的物件。HttpClient 在宣告時就要多加一個 HttpClientHandler 物件:
HttpClientHandler handler = new HttpClientHandler();
HttpClient client = new HttpClient(handler);
client.BaseAddress = new Uri(@"https://www.google.com");
而 HttpClient 在做 Get 或 Post 後,取出 HttpClientHandler 裡的 CookieContainer,就能取出 Cookie 了。
HttpResponseMessage response = await client.GetAsync(@"/");
CookieContainer cookieContainer = handler.CookieContainer;
IEnumerable<Cookie> responseCookies = handler.CookieContainer.GetCookies(client.BaseAddress).Cast<Cookie>();
foreach (Cookie cookie in responseCookies)
{
Console.WriteLine($"Key: {cookie.Name}, Value: {cookie.Value}");
Console.WriteLine();
}
參考資料