如何在调用WEB API后获取JSON响应字符串

时间:2014-01-17 01:23:35

标签: http asp.net-web-api

我试图从WEB API调用中获取结果,但我找不到检索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

调用WEB API后的Fiddler结果:

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 个答案:

答案 0 :(得分: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