我是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响应结果并需要访问它的值。
当我在调试模式下检查响应时,我看不到所有的响应值。那个项目还能给我所有的价值吗?我确定我做错了什么但如果有人帮我发现那会很棒。
答案 0 :(得分:2)
您可以查看https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse(v=vs.110).aspx以获取有关如何获取响应的httpBody的详细说明。使用.getResponse()获得响应后,您可以获取响应Stream并从变量中读取内容。
如链接文章中所述:
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(至少使用新的网络核心(mvc vnext))。我必须完全记住这个方法..