user414967
user414967

Reputation: 5325

spring boot character encoding response

In my spring boot application, I am getting a Json response in the below format by RestTemplate. However, when I tested the same in url directly in the broswer, I am getting proper JSON response.It is a hello.gz format. Is it the issue with character encoding?

BÈ\u001Bå%\u0011Áfbâÿ|yÇoþ\u0019Y¤Zb\u000E©¿ÛÆzùÝÖ½6\u001AÔ~ü\u0019\u009B£IVY¯u¥\u008B\u0012\u0017f¿Ùü\u0099ߧ¸\u0081p¢\u0084üÿ\u0016ûl 8\u009B\u0081MƵ\u001F«\u0006\u0085vz\u001Deúz¬Í¤×åê\u0010\u000E"{¡£/É¡Ò\u0090rHù\u0096¼\u009C±cc\u0004\u000F÷bÀ °N\u0081\u0002µÊ\u0087Ì,2£ChÖ\u0001~ð \u000BN?¨´>5ÀTvÔ\u001CÞC£\u009F>Þ*lÆ£Ú\u008FC\u00831þªÀmÙ+uWÎ8ëý\u0083`\u0086SñË\u0099¢yC\u000B\u0018£÷ñU´Æè&+b\u0018Ô~éÆ\u0083°ùFgÉÈ\u0088\uFFFD L;

I added the below lines to the applcation.properties.

spring.http.encoding.charset=UTF-8
# Enable http encoding support.
spring.http.encoding.enabled=true
# Force the encoding to the configured charset on HTTP requests and responses.
spring.http.encoding.force=true

Also I enabled GZip compression in Spring Boot

# Enable response compression
server.compression.enabled=true

# The comma-separated list of mime types that should be compressed
server.compression.mime-types=text/html,text/xml,text/plain,text/css,text/javascript,application/javascript,application/json

# Compress the response only if the response size is at least 1KB
server.compression.min-response-size=1024

Below is my code.

@GetMapping(value = { "/", "/hello" }, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> hello() {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<String>(null, headers);

        RestTemplate restTemplate = new RestTemplate();
        //restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
        ResponseEntity<String> entity2 = restTemplate.exchange(
                "https://XXXXX.8080/hello.gz", HttpMethod.GET, null,
                String.class);
        String body = entity2.getBody();

        System.out.println(body);

        return ResponseEntity.ok(body);
    }

Upvotes: 1

Views: 6736

Answers (1)

G. Spyridakis
G. Spyridakis

Reputation: 441

Replacing MediaType.APPLICATION_JSON_VALUE to MediaType.APPLICATION_JSON_UTF8_VALUE should work.

Otherwise try adding a message converter, with the UTF-8 charset, to the RestTemplate:

RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters()
        .add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));

Upvotes: 2

Related Questions