2014-01-17 51 views
0

我想從WEB API調用中獲取結果,但無法找到檢索JSON結果的方法。 這裏是一個調用Web API代碼:如何在調用WEB API後獲取JSON響應字符串

string baseAddress = "http://server001/"; 
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(baseAddress + "API/Import"); 
req.Method = "POST"; 
req.ContentType = "application/x-www-form-urlencoded"; 
Stream reqStream = req.GetRequestStream(); 
string fileContents = xml; 
byte[] fileToSend = Encoding.UTF8.GetBytes(fileContents); 
reqStream.Write(fileToSend, 0, fileToSend.Length); 
reqStream.Close(); 
HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); 
Console.WriteLine("HTTP/{0} {1} {2}", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription); 
//string jsonResult = resp. <=== here 

提琴手調用Web API後的結果:

HTTP/1.1 200 OK 
Cache-Control: no-cache 
Pragma: no-cache 
Content-Type: application/json; charset=utf-8 
Expires: -1 
Server: Microsoft-IIS/8.0 
X-AspNet-Version: 4.0.30319 
X-Powered-By: ASP.NET 
Date: Fri, 17 Jan 2014 01:10:00 GMT 
Content-Length: 57 

{"isError":false,"Msg":"Server data added successfully."} 

謝謝!

回答

0

這看起來像C#。 .NET文檔提供了一個很好的例子。您將要調用的GetResponseStream()的響應對象:

  // Creates an HttpWebRequest with the specified URL. 
      HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url); 

      // Sends the HttpWebRequest and waits for the response.   
      HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); 

      // Gets the stream associated with the response. 
      Stream receiveStream = myHttpWebResponse.GetResponseStream(); 
      Encoding encode = System.Text.Encoding.GetEncoding("utf-8"); 

      // Pipes the stream to a higher level stream reader with the required encoding format. 
      StreamReader readStream = new StreamReader(receiveStream, encode); 

      Console.WriteLine("\r\nResponse stream received."); 
      Char[] read = new Char[256]; 

      // Reads 256 characters at a time.  
      int count = readStream.Read(read, 0, 256); 
      Console.WriteLine("HTML...\r\n"); 

      while (count > 0) 
      { 
        // Dumps the 256 characters on a string and displays the string to the console. 
        String str = new String(read, 0, count); 
        Console.Write(str); 
        count = readStream.Read(read, 0, 256); 
      } 

      Console.WriteLine(""); 

      // Releases the resources of the response. 
      myHttpWebResponse.Close(); 

      // Releases the resources of the Stream. 
      readStream.Close(); 

來源:http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.getresponsestream(v=vs.110).aspx

+0

對!謝謝! – Max