Как получить строку ответа JSON после вызова WEB API

Я пытаюсь получить результаты от вызова API WEB, но я не могу найти метод, который извлекает результаты JSON. Вот код, который вызывает WEB API:

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

Результаты Fiddler после вызова 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."}

Спасибо!

1 ответ

Это похоже на С#. Хороший пример - документация.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.

licensed under cc by-sa 3.0 with attribution.