3

I'm trying to send

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

in my Spring boot application.

I'm getting this Exception

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

But I need to send gzip as request header.

My Spring boot Version is '1.3.5.RELEASE'

Please help me out.

My Request Example:

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);
}
Bertrand Martel
  • 42,756
  • 16
  • 135
  • 159
Bhaskar
  • 101
  • 1
  • 5
  • It might not be related to header. Could you (a) share the controller and request example and (b) try without header? – Darshan Mehta Apr 17 '17 at 09:34
  • Does this help: http://stackoverflow.com/questions/21410317/using-gzip-compression-with-spring-boot-mvc-javaconfig-with-restful – Marged Apr 19 '17 at 21:06
  • Yeah I have tried with that but didn't get the solution. – Bhaskar Apr 20 '17 at 07:41
  • But I got solution from http://stackoverflow.com/questions/34415144/cannot-parse-gzip-encoded-response-with-resttemplate-from-spring-web – Bhaskar Apr 20 '17 at 07:42

1 Answers1

0

I wanted to solve the same issue without using additional libraries. What helped me was to

  1. change the responseType from the entity type (GenericResponseDto) to byte[].class
  2. unzipping response myself
  3. mapping the entity myself by ObjectMapper mapper.

It is not the most elegant solution but it works.

    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());
fascynacja
  • 1,625
  • 4
  • 17
  • 35