Sending Gzip compressed data with Spring Android RestTemplate?

核能气质少年 提交于 2019-12-22 09:47:07

问题


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?


回答1:


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




回答2:


Just to share my working code for RestTemplate request 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 source code in answer of @Stoozi not work for me (if you use it simple will not receive compressed response) I have test 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

Response:

HTTP/1.1 200 OK
Content-Type: application/json
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 204
Server: Jetty(9.2.2.v20140723)

its need to use setAcceptEncoding() instead of setContentEncoding() in RestTemplate REQUEST headers.



来源:https://stackoverflow.com/questions/27446912/sending-gzip-compressed-data-with-spring-android-resttemplate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!