如何获取发送API请求和获取Json响应c#

本文关键字:获取 求和 请求 Json 响应 API 何获取 | 更新日期: 2023-09-27 18:11:36

我是API测试的新手,我只是想知道如何才能从c#中发出的请求中读取响应。

例如,我有一个API url:- http://api.test.com/api/xxk/jjjj?limit=30

            HttpWebRequest request = WebRequest.Create("http://api.test.com/api/xxk/jjjj?limit=30") as HttpWebRequest;
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                var res = response;
            }

这是给我的响应,但我需要得到所有的Json响应结果,并需要访问它的值。

当我检查在调试模式的响应,我不能看到所有的响应值。还有哪个对象会给我所有的值?我肯定我做错了什么,但如果有人能帮我查出来,那就太好了。

如何获取发送API请求和获取Json响应c#

您可以查看https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse(v=vs.110).aspx了解如何获取响应的httpBody的详细说明。在使用. getresponse()获得响应后,您可以获得响应流并在变量中读取其中的内容。

如链接文章所述:

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create (args[0]);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
        Console.WriteLine ("Content length is {0}", response.ContentLength);
        Console.WriteLine ("Content type is {0}", response.ContentType);
        // Get the stream associated with the response.
        Stream receiveStream = response.GetResponseStream ();
        // Pipes the stream to a higher level stream reader with the required encoding format. 
        StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);
        Console.WriteLine ("Response stream received.");
        Console.WriteLine (readStream.ReadToEnd ());
        response.Close ();
        readStream.Close ();

输出将是:

/*
The output from this example will vary depending on the value passed into Main 
but will be similar to the following:
Content length is 1542
Content type is text/html; charset=utf-8
Response stream received.
<html>
...
</html>
*/

With:

var res = readStream.ReadToEnd();

您将获得字符串形式的json主体。在此之后,您可以使用json解析器来解析它,如Newtonsoft.JSON。

我希望这至少回答了你的问题的70%。我认为有很多方法可以编写一个API来自动解析JSON主体(至少在新的net core (mvc vnext)中)。我必须准确地记住方法。