开发者

how do I stream data from an HTTPResponse to the console?

开发者 https://www.devze.com 2023-02-15 10:11 出处:网络
I am writing a console application that needs to receive a large amount of data. I tried to code it like this,

I am writing a console application that needs to receive a large amount of data. I tried to code it like this,

 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
 request.Method = "GET";
 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
 using (StreamReader sr = new StreamReader(response.GetResponseStream()))
 {
      responseText = sr.ReadToEnd();
 }

 Console.WriteLine(responseText);

But this code needs to wait for the entire response to writ开发者_运维技巧e out the data to the console. How can I recode this to stream the data to the console as it is being received?

Thanks.


If you are getting a large data, you will need to use HttpWebRequest asynchronously.

Use HttpWebRequest.BeginGetResponse()

HttpWebRequest webRequest;
void StartWebRequest()
{
   webRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest),null);
}
void FinishWebRequest(IAsyncResult result)
{
   webRequest.EndGetResponse(result);
}

When the asynchronous operation is complete, a callback function is been called. You need to at least call EndGetResponse() from this function.


Try reading one line at a time: ReadLine():

        while (!sr.EndOfStream)
        {
            responseText = sr.ReadLine();
            Console.WriteLine(responseText);
        }


char[] chars = new char[1024];
int numread = 0;
while ((numread = sr.Read(chars, 0, chars.Length)) > 0)
   Console.Write(new string(chars));
Console.WriteLine();


That's what ReadToEnd() means.

To write everything to a file:

 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
 request.Method = "GET";
 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
 var responseStream = response.GetResponseStream();
 using (var fileStream = new FileStream("C:\\temp\\myfile.avi"))
 {
     var buffer = new byte[8192];
     while (true)
     {
          var bytesRead = responseStream.Read(buffer, 0, buffer.Length);
          if (bytesRead <= 0)
              break;
          fileStream.Write(buffer, 0, bytesRead);
     }
 }
0

精彩评论

暂无评论...
验证码 换一张
取 消