OkHttp’s Gzip Compression

Abhishek Jain
Tech Insider
Published in
3 min readMay 1, 2020

--

Compression is a simple and effective way to save bandwidth and speed up your Mobile User Interaction. When a user hits your screen, there is a call that is made to your server to deliver the requested response. The bigger the response is, the longer it’s going to show data on your screen. With compression, Your visitors will enjoy fast loading even if they have a very slow Internet connection and your API responses are too heavy.

How does this work?

Gzip locates similar strings and replaces those strings temporarily with some placeholders to make the overall size smaller. If you use a lot of repeated text and have loads of whitespace then go for it. you can use Gzip to compress your Response Body as well as your Request body. This operation drastically reduces transfer time since the files are much smaller.

NOTE: If you are trying with the postman, it by default adds Accept-Encoding: gzipheader in the hidden headers section for you.

IMPORTANT: OkHttp Automatically adds the header Accept-Encoding in request and respects the Content-Encoding and therefore decompresses the Response data by itself, So no need to set it separately, but let’s say when we have to send compressed Request data to Server, then we have to write our own Interceptor.

The tricky part of this compression is that both Requester and server knowing it’s ok to send zipped files. The agreement has two parts:

You have to tell the server that you accept this encoding then it will provide.

  • The Requester sends a header telling to the server it accepts compressed content: Accept-Encoding: gzip
  • The server acknowledges your request with this header : Content-Encoding: gzip

Enough talking, I think I still have your attention So let’s see some code.

Writing Own Interceptors :

Pre-Requisite: Understanding of okhttp Interceptors.

  1. Unravel Gzip Response: Adding Accept-Encoding: gzip in the request header and while fetching the response look forContent-Encoding: gzip in its response header. If it is present that unzip it else return the response.

2. Creating a Gzip Request: If your Request size is too heavy then we can compress our request using this. To notify the server we will add Content-Encoding: gzip to request header.

and we are done, shower claps if you like it.

References :

  1. https://square.github.io/okhttp/
  2. https://www.apphp.com/tutorials/index.php?page=gzip-and-deflate-compression-in-web-development
  3. https://en.wikipedia.org/wiki/Gzip
  4. https://www.youtube.com/watch?v=Mjab_aZsdxw

--

--

Abhishek Jain
Tech Insider

Android dev | Software developer at InMobi, Ex- MMT, Tokopedia