我正在使用C#和HttpClient类尝试在Spotify登录页面获取cookies。然而,当我知道有cookie被设置时,CookieContainer总是为空。我没有发送任何头文件,但它仍应该给我cookie(s),因为当我使用Python(requests模块)发送不带任何头文件的GET请求时,我得到了csrf令牌。这是我的代码:
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Collections;
using System.Web;
class Program
{
static void Main()
{
Task t = new Task(MakeRequest);
t.Start();
Console.WriteLine("Getting cookies!");
Console.ReadLine();
}
static async void MakeRequest()
{
CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
Uri uri = new Uri("https://accounts.spotify.com/en/login/?_locale=en-US&continue=https:%2F%2Fwww.spotify.com%2Fus%2Faccount%2Foverview%2F");
HttpClient client = new HttpClient(handler);
var response = await client.GetAsync(uri);
string res = await response.Content.ReadAsStringAsync();
Console.WriteLine(cookies.Count);
foreach (var cookie in cookies.GetCookies(uri)) {
Console.WriteLine(cookie.ToString());
}
}
}
对我来说看起来很简单,但程序总是显示没有 cookie。 有人知道发生了什么吗?
handler.UseCookies
上启用了 cookie 吗? - NkosiUseCookies = true
是默认设置。我建议使用静态 HttpClient。可能是Lazy<HttpClient> httpClient = new Lazy<HttpClient>(() => { HttpClientHandler handler = new HttpClientHandler { (在此处设置新的 CookieContainer 或使用静态的 -> 以存储所有“会话”的 Cookies) } 等等 }
。在我看来,它在所有情况下都能更好地工作。 - Jimi