我得到了代码,发送GET请求并在流中接收答案。我用流阅读器阅读流到结束。这是代码:
HttpWebRequest requestGet = (HttpWebRequest)WebRequest.Create(url);
requestGet.Method = "GET";
requestGet.Timeout = 5000;
HttpWebResponse responseGet = (HttpWebResponse)requestGet.GetResponse();
StreamReader reader = new StreamReader(responseGet.GetResponseStream());
StringBuilder output = new StringBuilder();
output.Append(reader.ReadToEnd());
responseGet.Close();
但我不喜欢该程序等到收到所有数据后才开始使用响应。如果我能这样做(伪代码),那就太好了:
//here sending GET request
do
{
response.append(streamPart recieved);
//here work with response
} while (stream not ended)
我尝试了streamReader.Read(char[],int32_1,int32_2),但我无法指定int32_2,因为我不知道我收到了多少符号。如果我使用 ReadToEnd - 它会等待所有响应加载。
Read 采用char[]
缓冲区并返回从流中读取的字符数。下面是如何以块为单位读取响应的示例:
public static void Main(string[] args)
{
var req = WebRequest.Create("http://www.google.com");
req.Method = "GET";
req.Timeout = 5000;
using (var response = req.GetResponse())
using (var reader = new StreamReader(response.GetResponseStream()))
{
char[] buffer = new char[1024];
int read = 0;
int i = 0;
do
{
read = reader.Read(buffer, 0, buffer.Length);
Console.WriteLine("{0}: Read {1} bytes", i++, read);
Console.WriteLine("'{0}'", new String(buffer, 0, read));
Console.WriteLine();
} while(!reader.EndOfStream);
}
}
我没有看到任何多余的空格或重复的数据。