2

I am using Spring Boot to integrate to a third party which can provide gzipped responses and I want to log the size of the compressed response body vs the decompressed so we can audit for billing etc.

I'm using RestTemplate.exchange to make the GET request and the response is coming back correctly however I am unable to retrieve the Content-Length header in the response.

I know that the third party are sending it back because I can see it when I make the same request using Curl:

HTTP/1.1 200 OK
Date: Mon, 04 Feb 2019 15:40:10 GMT
Server: Apache
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 558
Connection: close
Content-Type: application/json

This is my Java code making the request and logging the lengths:

final ResponseEntity<String> responseEntity = restTemplate.exchange(url, GET, entity, String.class);
final String body = responseEntity.getBody();
LOG.info("Payload sizes: compressed={}, uncompressed={}", responseEntity.getHeaders().getContentLength(), body.length());

For the request headers I am setting 'Accept-Encoding: gzip,deflate' as per the documentation for the third party. However when I get the response the call to getContentLength() just returns -1. I've done a lot of searching around on this and tried using a ClientHttpRequestInterceptor but no joy.

Anybody ever had the same issues?

Glamdring
  • 69
  • 2
  • 7
  • What headers are in the response? It's possible that the server is using chunked transfer encoding when you make the request with `RestTemplate`. There's no `Content-Length` header when chunked encoding is in use. – Andy Wilkinson Feb 04 '19 at 17:47
  • Yeah I did check that as I'd read about that also but that didn't make sense. These are the headers that are returned when I read them from the RestTemplate response. `Date=[Mon, 04 Feb 2019 14:23:53 GMT], Server=[Apache], Vary=[Accept-Encoding], Connection=[close], Content-Type=[application/json]` As you can see I'm missing a couple compared with the response from Curl – Glamdring Feb 05 '19 at 08:42
  • That's rather odd. If anything, it looks like a problem on the server side. You could try enabling low level tracing of the HTTP client that you're using to verify that the headers aren't being lost once the response reaches the client. – Andy Wilkinson Feb 05 '19 at 09:07
  • Good advice, that's what it seems like to me too, thanks I will try that :) – Glamdring Feb 05 '19 at 09:08

1 Answers1

0

Just in case anyone got same issue as I had, if you are using TestRestTemplate, it will not show Content-Encode when gzip, try use RestTemplate instead

ExploreEv
  • 725
  • 8
  • 8