春季启动字符编码响应

时间:2018-12-09 15:53:54

标签: spring spring-mvc spring-boot

在我的spring boot应用程序中,我通过RestTemplate得到以下格式的Json响应。但是,当我直接在浏览器中在url中测试相同时,我得到了正确的JSON响应。它是hello.gz格式。 字符编码是否有问题?

BÈ\u001Bå%\u0011Áfbâÿ|yÇoþ\u0019Y¤Zb\ u000E©¿ÛÆzùݽ½6\u001AÔ〜ü\ u0019 \ u009B£IVY¯u¥\ u008B \ u0012 \u0017f¿Ùü\u0099ߧÿ\ u0084p \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 \ u00 ÷ñU´Æè&+ b \u0018Ô〜éÆ\ u0083°ùFgÉÈ\ u0088 \ uFFFD L;

我在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

下面是我的代码。

@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);
    }

1 个答案:

答案 0 :(得分:0)

MediaType.APPLICATION_JSON_VALUE替换为MediaType.APPLICATION_JSON_UTF8_VALUE应该可以。

否则,请尝试将带有UTF-8字符集的消息转换器添加到RestTemplate

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