【问题标题】:Async reading chunked content with HttpClient from ASP.NET WebApi使用 HttpClient 从 ASP.NET WebApi 异步读取分块内容
【发布时间】:2012-09-21 15:26:58
【问题描述】:

我想使用 HttpClient 异步读取分块(在 HTTP 1.1 分块传输编码的意义上)内容。

我正在查看 HttpContent 异步方法: MSDN link

但是,在返回Task为字节数组的情况下,例如:

返回的Task对象将在所有内容写入字节数组后完成

我得到分块的内容正是因为服务器不提前知道所有数据何时可用,因此我不知道所有内容何时到达。我希望能够在块到达时读取它们,而不是等待可能几个小时才能完成任务。

我能否以某种方式读取响应内容的一部分,例如在每收到 4K 字节的内容作为响应时完成某些任务?

在这种情况下使用 HttpClient 有优势吗?

【问题讨论】:

    标签: http rest asynchronous asp.net-web-api


    【解决方案1】:

    使用 HttpClient.SendAsync,您可以传递一个 HttpCompletionOption 参数来告诉 HttpClient 不要为您缓冲响应并在它获得标头后立即返回。然后,您可以使用 ReadAsStreamAsync 获取一个流,该流允许您在数据到达时提取数据。

    【讨论】:

    • 工作得很好。我使用了 HttpSelfHostServer 并确保内容被分块。我可以在客户端分块跟踪它的到来。无需手动解析分块的内容 - 在传输编码的意义上,流已经被解分块,即使数据以块的形式可用。
    【解决方案2】:

    Here 是一个完整的示例,说明如何下载文件而不将其内容读入内存,并附有说明。效果很好。

    static async Task HttpGetForLargeFileInRightWay()
    {
        using (HttpClient client = new HttpClient())
        {
            const string url = 
    "https://github.com/tugberkugurlu/ASPNETWebAPISamples/archive/master.zip";
            using (HttpResponseMessage response = await client.GetAsync(url, 
    HttpCompletionOption.ResponseHeadersRead))
            using (Stream streamToReadFrom = await response.Content.ReadAsStreamAsync())
            {
                string fileToWriteTo = Path.GetTempFileName();
                using (Stream streamToWriteTo = File.Open(fileToWriteTo, FileMode.Create))
                {
                    await streamToReadFrom.CopyToAsync(streamToWriteTo);
                }
            }
        }
    }
    

    或者你可以使用StreamReader而不是CopyToAsync()来读取流

    using (var stream = await response.Content.ReadAsStreamAsync())
    using (var reader = new StreamReader(stream))
    {
        int bytesCount = 100;
        var buffer = new char[bytesCount];
        reader.ReadBlock(buffer, 0, bytesCount);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多