如何使用 C# 从网站捕获 Json

How to capture Json from web site using c#

我付费订阅了 Seeking Alpha,并且有一个 cookie 可以让我从 https://seekingalpha.com/symbol/AAPL/financials-data?period_type=quarterly&statement_type=income-statement&order_type=latest_left&is_pro=True

获取完整数据

我想使用 C#

收集 JSON 响应

下面是我可怕的代码

        string cookie = "my super secret cookie string";


        var request = new RestRequest(Method.GET);
        request.AddHeader("content-type", "application/json");
        request.AddHeader("Accept", "*/*");
        request.AddHeader("User-Agent","Mozilla/5.0");
        request.AddHeader("X-Requested-With", "XMLHttpRequest");
        string url = "https://seekingalpha.com/symbol/AAPL/financials-data?period_type=quarterly&statement_type=income-statement&order_type=latest_left&is_pro=True";

                    request.AddParameter("cookie", cookie, ParameterType.Cookie);

        var client = new RestClient(url);

        var queryResult = client.Execute(request);

        Console.WriteLine(queryResult.Content);

我怎样才能 return JSON 给我?我得到了一些东西,但不是我想要的JSON

尝试将您的 Access header 更新为 application/json

request.AddHeader("Accept", "application/json");

Accept indicates what kind of response from the server the client can accept.

您可以从 Header parameters: “Accept” and “Content-type” in a REST context

获取有关 Accept 的更多信息

经过一番摸索,我明白了。为了大家的利益:

    private bool FinancialStatement(string symbol, string statement, string period)
    {
        var target = $"{BASE_URL}{symbol}/financials-data?period_type={period}&statement_type={statement}&order_type=latest_left&is_pro=True";

        var client = new RestClient(target);

        client.Timeout = -1;
        var request = new RestRequest(Method.GET);
        request.AddHeader("Cookie", MACHINE_COOKIE);
        IRestResponse response = client.Execute(request);
        dynamic responseObj;
        try
        {
            responseObj = JsonConvert.DeserializeObject(response.Content);
        }
        catch (Exception)
        {
            return false;
        }

        return response.IsSuccessful;
    }