spring-android

Sending Gzip compressed data with Spring Android RestTemplate?


The current Spring Android documentation says in section 2.2.2:

RestTemplate supports sending and receiving data encoded with gzip compression.

However, this document explains in section 2.7.2 how to receive Gzip data, but there is nothing about sending gzip data (using a POST or a PUT). Is it a missing feature so the introduction would be erroneous? Or is there some secret way to enable gzip compression?


Solution

  • GZip compression on requests is based on the "Content-Encoding" header of the request being handled by the RestTemplate. Setting this header to "gzip" will enable Gzip compression for your request. Luckily there are some constants and helper functions available to make this easy:

    HttpHeaders headers = new HttpHeaders();
    headers.setContentEncoding(ContentCodingType.GZIP);
    //...then use headers when making request with RestTemplate instance
    

    Be wary when using a ClientHttpRequestInterceptor with Gzip compression enabled as this will compress your request body multiple times (depending on how many interceptors you have configured) as I describe here: RestTemplate with ClientHttpRequestInterceptor causes GZIP compression twice