java 如何发送GZIP(接受编码: gzip)参数在请求头Sping Boot 应用程序?

vojdkbi0  于 2023-05-21  发布在  Java
关注(0)|答案(1)|浏览(224)

我正试着发送

headers.add("Accept-Encoding", "gzip");

在我的Sping Boot 应用程序中。
我得到了这个异常

com.fasterxml.jackson.core.JsonParseException: Illegal character ((CTRL-CHAR, code 31)): only regular white space (\r, \n, \t) is allowed between tokens

但是我需要发送gzip作为请求头。
我的Sping Boot 版本是'1.3.5.RELEASE'
请帮帮我
我的请求示例:

url = apiUrl + apiMethod + "?api_key=" + apiKey;

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("api_key", apiKey);
headers.add("Content-Type", "application/json");
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.set("Accept-Encoding", "x-gzip");
HttpEntity < String > entity = new HttpEntity < String > ("parameters", headers);
ResponseEntity < GenericResponseDto > response = null;
try {
    response = restTemplate.exchange(url, HttpMethod.GET, entity,
        GenericResponseDto.class);
    log.info("Response :" + response.toString());

} catch (Exception e) {
    throw new CustomException(e, aPIAuditTrail);
}
y4ekin9u

y4ekin9u1#

我想在不使用额外库的情况下解决同样的问题。帮助我的是
1.将responseType从实体类型(GenericResponseDto)更改为byte[].class
1.解压缩响应我自己
1.通过ObjectMapperMap器自己Map实体。
这不是最优雅的解决方案,但它有效。

ResponseEntity<byte[]> response = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<byte[]>(new HttpHeaders()), byte[].class);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    try (GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(response.getBody()))) {
        gzipInputStream.transferTo(byteArrayOutputStream);
    }
    byte[] content = byteArrayOutputStream.toByteArray();
    GenericResponseDto question = mapper.readValue(content, GenericResponseDto .class);  
    log.info("Response :" + question.toString());

相关问题