How to compress http request on the fly and without loading compressed buffer in memory

前端 未结 1 948
一生所求
一生所求 2021-02-04 10:22

I need to send voluminous data in a http post request to a server supporting gziped encoded requests.

Starting from a simple

public async Task

        
相关标签:
1条回答
  • 2021-02-04 10:59

    Try using the CompressedContent class from WebAPIContrib https://github.com/WebApiContrib/WebAPIContrib/blob/master/src/WebApiContrib/Content/CompressedContent.cs

    public async Task<string> DoPost(HttpContent content)
    {
      HttpClient client = new HttpClient();
      HttpResponseMessage response = await client.PostAsync("http://myUri", 
                                     new CompressedContent(content,"gzip"));
    
      response.EnsureSuccessStatusCode();
      return await response.Content.ReadAsStringAsync();
    }
    

    P.S. that this will only stream the content on .net 4.5. The .net 4 version of HttpWebRequest always buffers sent content.

    P.P.S. Creating a new HttpClient for each request is not the best way to use HttpClient. Doing this will force a new TCP connection to be created for each request.

    0 讨论(0)
提交回复
热议问题