如何使用Reatful API接口调用:GET方式
using System; using System.IO; using System.Net; using System.Text; // Create the web request HttpWebRequest request = WebRequest.Create("http://developer.yahoo.com/") as HttpWebRequest; // Get response using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { // Get the response stream StreamReader reader = new StreamReader(response.GetResponseStream()); // Console application output Console.WriteLine(reader.ReadToEnd()); }具体的请看链接:https://blog.csdn.net/boonya/article/details/46423989。
使用StreamReader调用Restful API接口发现无返回数据,报Length<错误:发生{System.NotSupportedException}类型的异常>。
查找了很多终于发现问题是GetResponseStream的流不支持Length。
修改代码后如下:
using (StreamReader reader = new StreamReader(myResponse.GetResponseStream()))
{
Stream responseStream = myResponse.GetResponseStream();
MemoryStream stmMemory = new MemoryStream();
byte[] buffer = new byte[64 * 1024];
int i;
while ((i = responseStream.Read(buffer, 0, buffer.Length)) > 0)
{
stmMemory.Write(buffer, 0, i);
}
byte[] arraryByte = stmMemory.ToArray();
stmMemory.Close();
BinaryReader binaryReader = new BinaryReader(responseStream);
binaryReader.Read(arraryByte, 0, (int)arraryByte.Length);
string msg = Encoding.GetEncoding("UTF-8").GetString(arraryByte);
System.Windows.Forms.MessageBox.Show("msg:" + msg);
}
可以获取返回数据。