2016-10-05 187 views
0

我是新來的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響應結果,並需要爲它訪問值。

當我檢查調試模式的響應我不能看到所有的響應值。還有哪個項目會給我所有的價值?我敢肯定,我做錯了什麼,但如果有人會幫我找出那會很好。

回答

2

你可以檢查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)中)。我必須牢記這個方法。