我有一个 API,我想调用它并获取响应。然后我想将该响应分配给一个变量。
我有一个像这样的 API:
http://example.org/Webservicesms_get_userbalance.aspx?user=xxxx&passwd=xxxx
当我在浏览器中运行此 URL 时,它会打印一条 SMS 余额。我想要此 SMS 余额作为响应,然后将其分配给我页面中的变量。
最佳答案
您也可以使用 WebRequest类。
WebRequest request = WebRequest.Create ("http://domainname/Webservicesms_get_userbalance.aspx?user=xxxx&passwd=xxxx");
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream ();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader (dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd ();
// Display the content.
Console.WriteLine (responseFromServer);
// Cleanup the streams and the response.
reader.Close ();
dataStream.Close ();
response.Close ();
当然,您可以将 Console.WriteLine
更改为您想要对响应执行的任何操作。
关于c# - 如何从 Web API 调用中获取响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7608527/