HTTP Compression - why wouldn't you use it? Image

HTTP Compression - why wouldn't you use it?

June 26, 2017      .net Programming

Now that I am firmly implanted in mobile apps development I can assume that data between my app and the server where data resides will be accessed using a limited connection (throttled at certain usage points, pay-as-your-go or otherwise).

The first thing I did was limit all my requests and responses to the bare minimum data needed. In other words, if a piece of data contains a big piece of information (like the body this blog post you're reading) I would grab it ONLY when needed. For example, to list blog posts, I would return only the title and date, for instance. And then I would make another request to fetch the body text only if the user clicks on the post to read it. Sensible, right?

But something still didn't sit right with me. There's got to be more I can do to reduce bandwidth usage, right?

Compression!

Of course, I should compress all data I send over the "wire" to make my minimal conversations eve smaller. But how? It turns out to be quite simple.

Since I'm already using WebAPI and HttpClient, there was surprisingly little to do.

I first checked the server to make sure compression was enabled. Luckily, it is enabled by default so I could check WebAPI off (since the JSON responses it sends would be compressed using the server's settings).

So what about the requests made by the app itself? Unfortunately, compression isn't on by default. Lucky for me it doesn't take much.

Since I make every request via a class I have derived from Microsoft's base HttpClient I merely had to add this to the constructor:

: base(new HttpClientHandler()
            {
                AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate
            })

 

The HttpClientHandler in bold tells the system to accept either of the standard web compression mechanisms and, if used by the server, automatically decompress the response.

Boom!

Using Telerik Fiddler to make sure things are working properly, I pleasantly see that compression is indeed working:

Wow - 51.3% compression? And that was on a very small response.

I'm sure my mileage will vary, but it was certainly worth the 20 minutes I spent!

I do wish this were enabled by default in the HttpClient subsystem, but as this article shows, it is quite easy to set up yourself.

Happy coding!

Share It