Sending compressed Gzip data using 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 nothing happens about sending gzip data (using POST or PUT). This is a missing feature, so the introduction would be wrong? Or is there some secret way to enable gzip compression?
source to share
GZip compression on request is based on the "Content-Encoding" header of the request processed by the RestTemplate. Setting this header to "gzip" will allow Gzip compression for your request. Fortunately, there are some constants and helper functions that make this easier:
HttpHeaders headers = new HttpHeaders();
headers.setContentEncoding(ContentCodingType.GZIP);
//...then use headers when making request with RestTemplate instance
Be careful when using ClientHttpRequestInterceptor
with Gzip compression enabled, as this compresses your request body multiple times (depending on the number of interceptors you configured) as I describe here:
RestTemplate with ClientHttpRequestInterceptor calls GZIP compression twice
source to share
Just to share my working code for requesting RestTemplate with AcceptEncoding: gzip
RestTemplate restTemplate = new RestTemplate();
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAcceptEncoding(ContentCodingType.GZIP);
HttpEntity<Coordinates> requestEntity = new HttpEntity<Coordinates>(coordinates, requestHeaders);
ResponseEntity<Integer> responseEntity = restTemplate.exchange(url, HttpMethod.PUT, requestEntity, Integer.class);
The original code in @ Stoozi's answer doesn't work for me (if you use it just don't get a concise response), I tested it with SoapUI
Request:
GET http://localhost:8081/jaxrs/admin-adblock
Accept:application/json
Cache-Control:no-cache
Content-Type:application/json
Authorization:Basic c21h...
Accept-Encoding:gzip,deflate
Answer:
HTTP/1.1 200 OK
Content-Type: application/json
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 204
Server: Jetty(9.2.2.v20140723)
must be used setAcceptEncoding()
instead setContentEncoding()
in REQUEST headers for RestTemplate.
source to share