How to parse gzip encoded response with RestTemplate in Spring-Web

后端 未结 2 683
-上瘾入骨i
-上瘾入骨i 2020-12-01 11:17

After I modified Consuming a RESTful Web Service example to call get users by id from api.stackexchange.com I get JsonParseException:

com.fasterxml.jackson.cor

相关标签:
2条回答
  • 2020-12-01 11:45
    private String callViaRest(String requestString, Steps step) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_XML);
        headers.add("Accept-Encoding", "application/gzip");
        HttpEntity<String> entity = new HttpEntity<String>(requestString, headers);
    
        byte[] responseBytes = jsonRestTemplate
                .exchange("yourUrl", HttpMethod.POST, entity, byte[].class).getBody();
        String decompressed = null;
        try {
            decompressed= new String(CompressionUtil.decompressGzipByteArray(responseBytes),Charsets.UTF_8);
        } catch (IOException e) {
            LOGGER.error("network call failed.", e);
        }
        return decompressed;
    }
    
    0 讨论(0)
  • 2020-12-01 12:09

    Replace the default requestFactory with one from Apache HttpClient (which decodes GZIP on the fly):

    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(
                HttpClientBuilder.create().build());
    RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
    

    Add Apache Http Client into pom.xml

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <!--Version is not needed when used with Spring Boot parent pom file -->
        <version>4.5.1</version>
    </dependency>
    
    0 讨论(0)
提交回复
热议问题