6 c# http httpwebrequest httpwebresponse
使用HttpWebRequest对象发出请求时,我需要调用方法GetResponse()来发送请求并获取响应.
此方法的问题在于,在收到所有数据之前,它不会返回响应对象.假设我正在下载一个100 MB的文件,在响应完成并且下载了所有100 MB之前,我将无法读取它.
我想要的是能够在它们到达时立即读取响应流字节,而无需等待响应完成.
我知道我可以使用Range Http标头,但它不适用于我的情况.
我认为这与@Zachary建议的非常接近.它(似乎)工作; 实际上我认为使用using
@Zachary确实是"更好".
我的主要观点是我无法看到GetResponse()
你(似乎)描述的阻塞行为.
此外,以下代码仅粗略地显示了一切如何工作; 例如,它不会将流读到最后(除非巧合:)).但是,如果将其复制粘贴到Visual Studio中的空"控制台应用程序"项目中,它应该可以工作.
您可以尝试使用一些"较短"的URL进行测试.这里的示例开始下载debian发行版的ISO(略大于600 MByte).对不起debian,我不是故意偷你的带宽. - >顺便说一下:有什么明智的东西可以用来测试这样的场景吗?
该代码受C#的强烈启发- 如何通过HTTP读取连续的XML流.
namespace StreamReadWebRequest
{
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
class Program
{
static void Main(string[] args)
{
HttpWebRequest req;
HttpWebResponse res = null;
try
{
req = (HttpWebRequest)WebRequest.Create(
"http://cdimage.debian.org/debian-cd/5.0.4/i386/iso-cd/debian-504-i386-CD-1.iso");
res = (HttpWebResponse)req.GetResponse();
Stream stream = res.GetResponseStream();
byte[] data = new byte[4096];
int read;
while ((read = stream.Read(data, 0, data.Length)) > 0)
{
Process(data, read);
}
}
finally
{
if (res != null)
res.Close();
}
Console.In.Read();
}
private static void Process(byte[] data, int read)
{
Console.Out.Write(ASCIIEncoding.ASCII.GetString(data));
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
26192 次 |
最近记录: |