gpt4 book ai didi

c# - 无法使用 C# HttpClient 获取任何 cookie

转载 作者:太空宇宙 更新时间:2023-11-03 12:08:01 29 4
gpt4 key购买 nike

我正在尝试使用 C# 和 HttpClient 类在 Spotify 登录页面上获取 cookie。但是,当我知道正在设置 cookie 时,CookieContainer 始终为空。我没有发送任何 header ,但它仍然应该给我 cookie,因为当我使用 python(请求模块)发送没有任何 header 的 GET 请求时,我得到了 csrf token 。这是我的代码:

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());
}
}
}

这对我来说似乎很简单,但程序总是说有 0 个 cookie。有人知道这是怎么回事吗?

最佳答案

您需要使用 HttpClientHandler.UseCookies Property 启用 cookie

public bool UseCookies { get; set; }

Gets or sets a value that indicates whether the handler uses the CookieContainer property to store server cookies and uses these cookies when sending requests.

//...

CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
handler.UseCookies = true; //<-- Enable the use of cookies.

//...

关于c# - 无法使用 C# HttpClient 获取任何 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53906224/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com