c# - 在内容 100% 完成之前从 HttpResponseMessage 读取 header

标签 c# asynchronous c#-5.0 dotnet-httpclient

  1. 如何在整个响应流回之前访问响应 header ?
  2. 如何在流到达时读取它?
  3. HttpClient 是我对接收 http 响应进行这种精细控制的最佳选择吗?

这里有一个片段可以说明我的问题:

using (var response = await _httpClient.SendAsync(request,
  HttpCompletionOption.ResponseHeadersRead))
{
   var streamTask = response.Content.ReadAsStreamAsync();
   //how do I check if headers portion has completed? 
   //Does HttpCompletionOption.ResponseHeadersRead guarantee that?
   //pseudocode
   while (!(all headers have been received)) 
     //maybe await a Delay here to let Headers get fully populated
   access_headers_without_causing_entire_response_to_be_received

   //how do I access the response, without causing an await until contents downloaded?
   //pseudocode
   while (stremTask.Resul.?) //i.e. while something is still streaming
     //? what goes here? a chunk-read into a buffer? or line-by-line since it's http?
   ...


编辑为我澄清另一个灰色区域:
我发现的任何引用都有某种阻塞语句,这会导致等待内容到达。 我阅读的引用通常访问 streamTask.Result 或内容上的方法或属性,但我不当 streamTask 正在进行时,我们知道足以排除哪些此类引用是可以的,哪些将导致等待直到任务完成。

最佳答案

根据我自己的测试,在您开始阅读内容流之前,内容不会被传输,调用 Task.Result 是一个阻塞调用是正确的,但它的本质,这是一个同步点。 但是,它不会阻塞以预先缓冲整个内容,它只会阻塞直到内容开始来自服务器。

因此无限流不会阻塞无限长的时间。因此,尝试异步获取流可能被认为是矫枉过正,尤其是当您的 header 处理操作相对较短时。但是,如果您愿意,您始终可以在另一个任务处理内容流时处理 header 。像这样的东西可以做到这一点。

static void Main(string[] args)
{
    var url = "http://somesite.com/bigdownloadfile.zip";
    var client = new HttpClient();
    var request = new HttpRequestMessage(HttpMethod.Get, url);

    var getTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
    Task contentDownloadTask = null;

    var continuation = getTask.ContinueWith((t) =>
    {
        contentDownloadTask = Task.Run(() =>
        {
            var resultStream = t.Result.Content.ReadAsStreamAsync().Result;
            resultStream.CopyTo(File.Create("output.dat"));
        });

        Console.WriteLine("Got {0} headers", t.Result.Headers.Count());
        Console.WriteLine("Blocking after fetching headers, press any key to continue...");
        Console.ReadKey(true);
    });

    continuation.Wait();
    contentDownloadTask.Wait();
    Console.WriteLine("Finished downloading {0} bytes", new FileInfo("output.dat").Length);

    Console.WriteLine("Finished, press any key to exit");
    Console.ReadKey(true);
}

请注意,无需检查 header 部分是否完整,您已使用 HttpCompletionOption.ResponseHeadersRead 选项明确指定了这一点。在检索到 header 之前,SendAsync 任务不会继续。

关于c# - 在内容 100% 完成之前从 HttpResponseMessage 读取 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15368066/

相关文章:

c# - Unity : Map Input. GetButtonDown ("Jump") 在iOS touch

c# - 使用 C# 将同步方法转换为异步方法

c# - wpf 应用程序中的异步/等待方法

c# - .NET async\await 基础知识

c# - 无法通过 Entity Framework 在 Azure 中使用代码优先方法创建 SQL 表

c# - 复杂类型作为 web api 操作中的可选参数

linux - Node JS : Executing command lines and getting outputs asynchronously

android - 强制我的 Activity 前景?

c# - 指针类型数组上的 foreach 的闭包语义