如何在Spring Boot应用程序的请求头中发送GZIP(Accept-Encoding:gzip)参数?

3
我正在尝试发送。
headers.add("Accept-Encoding", "gzip"); 

在我的Spring Boot应用程序中,我遇到了以下异常:
com.fasterxml.jackson.core.JsonParseException: Illegal character ((CTRL-CHAR, code 31)): only regular white space (\r, \n, \t) is allowed between tokens

但我需要将gzip作为请求头发送。

我的Spring 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);
}

可能与头文件无关。你能否(a)分享控制器和请求示例,以及(b)尝试不使用头文件? - Darshan Mehta
这个有帮助吗:https://dev59.com/2WEi5IYBdhLWcg3wUKyC - Marged
是的,我已经尝试过了,但没有得到解决方案。 - Bhaskar
但是我从https://dev59.com/01sW5IYBdhLWcg3w8q_2得到了解决方案。 - Bhaskar
1个回答

0

我想解决相同的问题,但不使用额外的库。

  1. 将responseType从实体类型(GenericResponseDto)更改为byte[].class
  2. 自己解压响应
  3. 通过ObjectMapper mapper自己映射实体。

这不是最优雅的解决方案,但它有效。

    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());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接