0

我得到了代码,它发送 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 - 它会等待所有响应加载。

4

1 回答 1

0

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);
        }
    }

我没有看到任何多余的空白或重复数据。

于 2013-09-09T01:22:21.783 回答