簡體   English   中英

如何在 c# 中檢索和使用通過 Http GET 請求獲得的數據

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

因此,我嘗試將 GET 請求與 c# 一起使用,但沒有任何效果。 我想使用站點https://covid19.mathdro.id/api作為測試,看看我是否可以從那里獲取信息並以 windows 形式使用它。 但我似乎無法弄清楚如何。 我發現的唯一指南並沒有那么有用,只是讓我更加困惑。 任何人都可以幫助我嗎?

我曾嘗試將 HttpClient 與 JSON.net 一起使用,但我對此感到困惑。 過去 2 小時一直在嘗試,因為除了 Python 之外,我從未處理過 c# 中的 HTTP GET 請求。

安裝“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);
}

除了接受的答案之外,您始終可以通過反序列化將數據作為對象處理 - 我更喜歡這種方法而不是使用JToken等,因為它往往很容易處理對象(通常很少有樣板可以從中提取數據位響應)。

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

您要反序列化的對象如下所示:

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

不過,這確實取決於偏好和您的用例。

例子:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM