Can I directly stream from HttpResponseMessage to file without going through memory?

前端 未结 2 1882
夕颜
夕颜 2021-01-11 18:28

My program uses HttpClient to send a GET request to a Web API, and this returns a file.

I now use this code (simplified) to store the file to disc:

p         


        
2条回答
  •  悲哀的现实
    2021-01-11 18:41

    Instead of GetAsync(Uri) use the the GetAsync(Uri, HttpCompletionOption) overload with the HttpCompletionOption.ResponseHeadersRead value.

    The same applies to SendAsync and other methods of HttpClient

    Sources:

    • docs (see remarks) https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.getasync?view=netcore-1.1#System_Net_Http_HttpClient_GetAsync_System_Uri_System_Net_Http_HttpCompletionOption_

    The returned Task object will complete based on the completionOption parameter after the part or all of the response (including content) is read.

    • .NET Core implementation of GetStreamAsync that uses HttpCompletionOption.ResponseHeadersRead https://github.com/dotnet/corefx/blob/release/1.1.0/src/System.Net.Http/src/System/Net/Http/HttpClient.cs#L163-L168

    • HttpClient spike in memory usage with large response

    • HttpClient.GetStreamAsync() with custom request? (don't mind the comment on response, the ResponseHeadersRead is what does the trick)

提交回复
热议问题