Search code examples
javaspringspring-boottomcat

How to remove Transfer-Encoding: chunking from a @RestController response?


I am writing a Spring Boot app that exposes a REST JSON API; however, some older clients cannot parse the JSON response because these numbers are present at the start and end of the response body:

Numbers

After a lot of searching and testing, I have come to the conclusion that those numbers are caused by Transfer-Encoding: chunking.

I have tried setting the Transfer-Encoding header manually, however it just gets ignored.

The proposed solution is quite messy as it requires modifying all the controller methods, as such, I would like to know if anyone has a more straightforward solution.


Solution

  • I have found a better solution: According to this response a ShallowEtagHeaderFilter can be registered to calculate the Content-Length of the response, effectively removing chunking.

        @Bean
        public FilterRegistrationBean<?> registerFilters()
        {
            FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>();
            registration.setFilter(new ShallowEtagHeaderFilter());
            registration.addUrlPatterns("/api/*");
            return registration;
        }