spring-bootencodingresttemplatehttp-getspring-resttemplate

Java Spring RestTemplate getForObject response not decoded properly


I am trying to execute a HTTP GET request that I can execute properly in Postman in my Spring Boot application using the RestTemplate class.

This is the code I am using to send the request:

RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject(url, String.class);

When I execute this the response variable contains only weird characters. My initial thought was that I was using the wrong encoding. The response I see in Postman indicates that the correct encoding is UTF-8, so I added this code:

restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));

I also though I was using the wrong "Accept" header, so I also added this code:

List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new HeaderRequestInterceptor("Accept", MediaType.ALL_VALUE));
restTemplate.setInterceptors(interceptors);

Both these adjustments do not fix the issue. Is there any other way to fix this?

I am happy to provide more info if needed! Thanks in advance.


Solution

  • The reason for this was that the response size was too big for my Spring Application. I had to use the WebClient class using the 'ExchangeStrategies':

    int size = 100000 * 1024;
    ExchangeStrategies strategies = ExchangeStrategies.builder()
                .codecs(codecs -> codecs.defaultCodecs().maxInMemorySize(size))
                .build();
    

    Also I had to set this property in the application.yml file:

    spring:
        codec:
           max-in-memory-size: 100MB
    

    These two adjustments fixed the request for me.