Jan
Jan

Reputation: 45

How do I retrieve and use data I get with Http GET Requests in c#

So I am trying to use GET requests with c# but nothing is really working out. I wanted to use the site https://covid19.mathdro.id/api as a test to see if I can get the info out of there and use it in a windows form. But I can't seem to figure out how. The only guides I found weren't really that helpful and it just confused me more. Would anyone be able to help me out?

I have tried to use the HttpClient with JSON.net but I get confused in it. Been trying for the past 2 hours since I never dealt with HTTP GET Requests in c# other than with Python.

Upvotes: 2

Views: 3566

Answers (2)

Andrew Arthur
Andrew Arthur

Reputation: 1603

Install the 'Newtonsoft.Json' nuget package.

async Task<JToken> GetREST(string uri)
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(uri);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        // HTTP GET
        HttpResponseMessage response = await client.GetAsync("");
        if (response.IsSuccessStatusCode)
        {
            var jsonData = await response.Content.ReadAsStringAsync();
            return JToken.Parse(jsonData);
        }
    }
    return null;
}

async private void button1_Click(object sender, EventArgs e)
{
    var jObj = await GetREST("https://covid19.mathdro.id/api");
    var confirmed = jObj["confirmed"];
    Console.WriteLine("Confirmed:" + confirmed["value"]);
    var confirmedJSON = await GetREST(confirmed["detail"].ToString());
    Console.WriteLine(confirmedJSON);
}

Upvotes: 2

Charleh
Charleh

Reputation: 14002

In addition to the accepted answer, you can always work with the data as objects by deserializing - I prefer this method over using JToken etc as it tends to be very easy to work with the objects (there's often less boilerplate to pull bits of data from the response).

        public async Task<CovidData> GetCovidData(string uri)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(uri);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = await client.GetAsync("");
                if (response.IsSuccessStatusCode)
                {
                    var jsonData = await response.Content.ReadAsStringAsync();
                    return JsonConvert.DeserializeObject<CovidData>(jsonData);
                }
            }
            return null;
        }

The objects you'd deserialize to would look like this:

    public class CovidData
    {
        public ValueDetailPair Confirmed { get; set; }

        public ValueDetailPair Recovered { get; set; }

        public ValueDetailPair Deaths { get; set; }
    }

    public class ValueDetailPair
    {
        public int Value { get; set; }

        // If you need the link to the detail it would be deserialized to this string member
        public string Detail { get; set; }
    }

It really does depend on preference and your use case though.

example:

var data = await GetCovidData("https://covid19.mathdro.id/api");

Console.WriteLine(data.Confirmed.Value);
Console.WriteLine(data.Confirmed.Detail);
Console.WriteLine(data.Recovered.Value);

Upvotes: 1

Related Questions