无法使用C#HttpClient获取任何cookie [英] Can't get any cookies with C# HttpClient

查看:131
本文介绍了无法使用C#HttpClient获取任何cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to get cookies on the Spotify login page with C# and the HttpClient class. However, the CookieContainer is always empty when I know cookies are being set. I'm not sending any headers, but it should still give me the cookie(s) because when I send a GET request without any headers with python (requests module) I get the csrf token. Here's my code:

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.有人知道发生了什么事吗?

It seems pretty simple to me, but the program always says there's 0 cookies. Anyone know what's going on?

推荐答案

我尝试使用Console.WriteLine(response.Headers)将响应标头写入控制台,并将带有csrf令牌的Set-Cookie标头打印到控制台安慰.因此,似乎HttpClient不会将此标头中的cookie视为实际cookie,因此不会将这些表示的cookie添加到CookieContainer中.

I tried to write the response headers to the console with Console.WriteLine(response.Headers) and a Set-Cookie header with the csrf token was printed to the console. So it seems that HttpClient doesn’t count cookies in this header as actual cookies, thus not adding these said cookies to the CookieContainer.

这篇关于无法使用C#HttpClient获取任何cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆