json C#中从API获取数据

iszxjhcz  于 12个月前  发布在  C#
关注(0)|答案(2)|浏览(198)

我尝试使用C#从开放的API获取数据。
在下面的代码中,我设法创建了一个HttpClient对象,但无法获得http响应。
已创建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);
            }
        }
    }
}

字符串

kxeu7u2r

kxeu7u2r1#

只需从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);
            }
        }
    }
}

字符串

rqcrx0a6

rqcrx0a62#

只需要等待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":"What was the name of the cancelled sequel of Team Fortress?","correct_answer":"Team Fortress 2: Brotherhood of Arms","incorrect_answers":["Team Fortress 2: Desert Mercenaries","Team Fortress 2: Operation Gear Grinder","Team Fortress 2: Return to Classic"]},{"category":"Entertainment: Video Games","type":"boolean","difficulty":"easy","question":"In "Super Mario 64", collecting 100 coins on a level will give you a 1-UP.","correct_answer":"False","incorrect_answers":["True"]},{"category":"Entertainment: Video Games","type":"boolean","difficulty":"easy","question":"Niko Bellic is the protagonist of Grand Theft Auto IV.","correct_answer":"True","incorrect_answers":["False"]},{"category":"Entertainment: Video Games","type":"multiple","difficulty":"easy","question":"What year did the game "Overwatch" enter closed beta?","correct_answer":"2015","incorrect_answers":["2013","2011","2016"]},{"category":"Entertainment: Video Games","type":"multiple","difficulty":"easy","question":"How many differently shaped Tetris pieces are there?","correct_answer":"7","incorrect_answers":["5","6","8"]},{"category":"Entertainment: Video Games","type":"multiple","difficulty":"easy","question":"What video game sparked controversy because of its hidden "Hot Coffee" minigame?","correct_answer":"Grand Theft Auto: San Andreas","incorrect_answers":["Grand Theft Auto: Vice City","Hitman: Blood Money","Cooking Mama"]},{"category":"Entertainment: Video Games","type":"multiple","difficulty":"easy","question":"The name of the Metroid series comes from what?","correct_answer":"An enemy in the game","incorrect_answers":["The final boss's name","The main character's name","A spaceship's name"]},{"category":"Entertainment: Video Games","type":"multiple","difficulty":"easy","question":"Which of the following was NOT a playable character in the game Kingdom Hearts: Birth by Sleep?","correct_answer":"Ignis","incorrect_answers":["Ventus","Terra","Aqua"]},{"category":"Entertainment: Video Games","type":"multiple","difficulty":"easy","question":"Who turns out to be the true victor in the Battle of Armageddon in Mortal Kombat?","correct_answer":"Shao Kahn","incorrect_answers":["Liu Kang","Shang Tsung","Raiden"]},{"category":"Entertainment: Video Games","type":"multiple","difficulty":"easy","question":"In "Mario & Sonic at the Olympic Games", characters are split into how many types?","correct_answer":"4","incorrect_answers":["6","5","3"]}]}

相关问题