如何获取发送API请求并获取Json响应c#
问题描述:
我是新来的API测试,我只想知道如何能够读取来自请求在C#中所做的响应。我在下面尝试。如何获取发送API请求并获取Json响应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响应结果,并需要为它访问值。
当我检查调试模式的响应我不能看到所有的响应值。还有哪个项目会给我所有的价值?我敢肯定,我做错了什么,但如果有人会帮我找出那会很好。
答
你可以检查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 = response.GetResponseStream().ReadToEnd();
您将得到JSON体中的字符串表示。在此之后,您可以使用像Newtonsoft.JSON这样的json解析器来解析它。
我希望这回答你的问题至少70%。我认为有很多方法可以编写一个自动分析JSON主体的API(至少在新的net core(mvc vnext)中)。我必须牢记这个方法。