简体   繁体   中英

How to capture Json from web site using c#

I have a paid subscription to Seeking Alpha and have a cookkie which enables me to get full data from https://seekingalpha.com/symbol/AAPL/financials-data?period_type=quarterly&statement_type=income-statement&order_type=latest_left&is_pro=True

I'd like to collect JSON response using C#

Below is my horrible code

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

How can I get it to return JSON to me? I am getting something but not the JSON I want

Try updating your Access header to application/json .

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

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

You can get more info for Accept from Header parameters: “Accept” and “Content-type” in a REST context

After poking around for a bit I figured it out. For the benefit of all:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM