How to send compressed request content using HTTP request

In this tutorial I will show how to send compressed content to a web api.

A lot of time when we develop a client application to consume a web api or send some data to web api, we do not have to deal with large set of data. If your client call is downloading data from server, then you specify appropriate Accept-Encoding http header value to dfalt, gzip etc. And when you get response you can decompress it. And if you are posting data to server then simple send data in form.

Recently I was working on an application where I had to send over 5MB data in request. To send such a large data set, you run into multiple issues. First publisher has to relax rules on web server to allow such a large size of request content. But doing so the server can be open to DOS attacks. And then you have to make sure that you set appropriate time out values in your request so that request can be completed before time out triggers.

Finally we decided that I will send request content as compressed. Publisher of API will look for appropriate header to decide if request content needs to be decompressed before processing or not. Here are the steps you will need to take on client side to send compressed request to publisher.

Create request client

        var client = new HttpClient(requestHandler)
                BaseAddress = new Uri("http://localhost/ProtoWebApi/"), 
                Timeout = TimeSpan.FromMilliseconds(10000)

Create compressed content

        public static HttpContent CompressRequestContent(string content)
            var compressedStream = new MemoryStream();
            using (var contentStream = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(content)))
                using (var gzipStream = new GZipStream(compressedStream, CompressionMode.Compress))
            var httpContent = new ByteArrayContent(compressedStream.ToArray());
            return httpContent;

Set encoding header on HttpContent

        compressedContent.Headers.Add("Content-encoding", "gzip");

Make http request

        var resp = httpClient.PutAsync(apiRequestUrl, compressedContent).Result;

This is all you will need to send compressed request content to publisher of web api.

comments powered by Disqus




15.7 °C / 60.3 °F

weather conditions Clear

Monthly Posts

Blog Tags