【问题标题】:How to get send API Request and get Json Response c# [duplicate]如何获取发送API请求并获取Json响应c# [重复]
【发布时间】:2016-10-05 02:03:27
【问题描述】:

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

例如,我有一个 API 网址:- 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 响应结果并需要访问它的值。

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

【问题讨论】:

    标签: c# api


    【解决方案1】:

    您可以查看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>
    
    */
    

    与:

    var res = readStream.ReadToEnd();
    

    您将以字符串表示形式获得 json 正文。在此之后,您可以使用像 Newtonsoft.JSON 这样的 json 解析器来解析它。

    我希望这至少能回答您 70% 的问题。我认为有一些方法可以编写一个自动解析 JSON 主体的 API(至少使用新的网络核心(mvc vnext))。方法我一定要牢牢记住。。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-05
      • 1970-01-01
      • 2011-12-21
      • 2019-02-23
      • 2011-07-06
      • 2020-11-19
      • 2023-02-01
      相关资源
      最近更新 更多