【问题标题】:Getting data from API in C#在 C# 中从 API 获取数据
【发布时间】:2020-03-03 10:17:21
【问题描述】:

我正在尝试使用 C# 从开放 API 获取数据。

在下面的代码中,我设法创建了一个 HttpClient 对象,但我无法获得 http 响应。我有一些Console.Writeline() 来帮助我定位错误,我打印的最后一件事是

创建的 HTTP 客户端

所以我似乎没有得到回应。谁能告诉我怎么回事?

using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace CodeTesting
{
    public class Parser
    {
        public Parser()
        {
            Console.WriteLine("Created parser");
            GetQuestion();
        }

        public static async void GetQuestion()
        {
            Console.WriteLine("INSIDE GETQUESTION");
            string baseUrl = "https://opentdb.com/api.php?amount=10&category=15&difficulty=easy";

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    Console.WriteLine("Created HTTPClient");

                    using (HttpResponseMessage res = await client.GetAsync(baseUrl))
                    {
                        Console.WriteLine("GOT HTTP RESPONSE");

                        using (HttpContent content = res.Content)
                        {
                            Console.WriteLine("RETRIEVING CONTENT");
                            var data = await content.ReadAsStringAsync();
                            if (data != null)
                            {
                                Console.WriteLine("data------------{0}", data);
                            }
                            else
                            {
                                Console.WriteLine("NO Data----------");
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("Exception Hit------------");
                Console.WriteLine(exception);
            }
        }
    }
}

【问题讨论】:

  • 您是遇到错误还是根本没有继续执行Console.WriteLine(("GOT HTTP RESPONSE");) 步骤?您的程序可能只是在等待响应。您是否尝试过在await client.GetAsync(baseurl) 行设置断点?
  • 您的代码永远不会等待GetQuestion() 完成。最有可能的是,它在收到响应之前终止。 不要在构造函数中调用异步方法
  • async void 仅用于事件处理程序,不能等待。将async Task 用于不返回数据的异步方法。
  • 尝试删除“等待”。 await 将阻塞直到连接关闭,而不是当您收到响应结束时。服务器没有关闭连接,所以你被阻止了。

标签: c# json api httpclient


【解决方案1】:

只需从 HttpResponseMessage 中删除 await 并在 GetAsync() 函数的末尾添加“.Result”,下面的代码就可以工作了。

using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

namespace CodeTesting
{
    public class Parser
    {
        public Parser()
        {
            Console.WriteLine("Created parser");
            GetQuestion();
        }
        public static async void GetQuestion()
        {
            Console.WriteLine("INSIDE GETQUESTION");
            string baseUrl = "https://opentdb.com/api.php?amount=10&category=15&difficulty=easy";

            try
            {

                using (HttpClient client = new HttpClient())
                {
                    Console.WriteLine("Created HTTPClient");

                    using (HttpResponseMessage res = client.GetAsync(baseUrl).Result)
                    {
                        Console.WriteLine("GOT HTTP RESPONSE");

                        using (HttpContent content = res.Content)
                        {
                            Console.WriteLine("RETRIEVING CONTENT");

                            var data = await content.ReadAsStringAsync();

                            if (data != null)
                            { Console.WriteLine("data------------{0}", data);}
                            else
                            { Console.WriteLine("NO Data----------"); }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("Exception Hit------------");
                Console.WriteLine(exception);
            }
        }
    }
}

【讨论】:

    【解决方案2】:

    只需等待 http 客户端获取值。 所以你的解析器会是这样的,

    public Parser()
            {
                Console.WriteLine("Created parser");
                GetQuestion();
                Console.ReadLine();
            }
    

    注意:这不是解决方案,但要解除阻止,请尝试此操作以便查看输出。

    输出:

    创建的解析器
    内部问题
    创建 HTTPClient
    得到 HTTP 响应
    检索内容
    data------------{"response_code":0,"results":[{"category":"Entertainment: Video Games","type":"multiple","difficulty":" easy","question":"被取消的军团要塞续集叫什么名字?","correct_answer":"军团要塞 2:兄弟会","incorrect_answers":["军团要塞 2:沙漠雇佣兵", "军团要塞 2:磨牙机行动","军团要塞 2:回归经典"]},{"category":"娱乐:电子游戏","type":"boolean","difficulty":"easy", “问题”:“在“超级马里奥 64”中,在一个关卡中收集 100 个硬币会给你一个 1-UP。”,“正确答案”:“错误”,“错误答案”:[“真”]},{“类别":"Entertainment: Video Games","type":"boolean","difficulty":"easy","question":"Niko Bellic 是 Grand Theft Auto IV 的主角。","correct_answer":"True" ,"incorrect_answers":["False"]},{"category":"娱乐:电子游戏","type":"multiple","difficulty":"easy","question":"游戏是哪一年“守望先锋”进入封闭测试版?","correct_answer":"2015","incorrect_ans wers":["2013","2011","2016"]},{"category":"娱乐:电子游戏","type":"multiple","difficulty":"easy","question": "有多少不同形状的俄罗斯方块?","correct_answer":"7","incorrect_answers":["5","6","8"]},{"category":"娱乐:视频游戏" ,"type":"multiple","difficulty":"easy","question":"哪款电子游戏因其隐藏的“热咖啡”小游戏而引发争议?","correct_answer":"侠盗猎车手:圣安地列斯","incorrect_answers":["Grand Theft Auto: Vice City","Hitman: Blood Money","Cooking Mama"]},{"category":"Entertainment: Video Games","type":"multiple", "difficulty":"easy","question":"银河战士系列的名字来源于什么?","correct_answer":"游戏中的敌人","incorrect_answers":["最终boss的名字","主角的名字","宇宙飞船的名字"]},{"category":"娱乐:电子游戏","type":"multiple","difficulty":"easy","question":"哪个以下不是游戏《王国之心:S》中的可玩角色leep?","correct_answer":"Ignis","incorrect_answers":["Ventus","Terra","Aqua"]},{"category":"娱乐:电子游戏","type":"multiple" ,"difficulty":"easy","question":"谁是真人快打世界末日之战的真正胜利者?","correct_answer":"Shao Kahn","incorrect_answers":["刘康","尚宗","雷电"]},{"category":"娱乐:电子游戏","type":"multiple","difficulty":"easy","question":"In "Mario & Sonic at the Olympic Games》,角色分为几种类型?","correct_answer":"4","incorrect_answers":["6","5","3"]}]}

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-01
      • 2021-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-23
      相关资源
      最近更新 更多