在我的 Spring 季启动应用程序中,我通过RestTemplate以下面的格式获得Json响应 . 但是,当我直接在broswer中测试url中的相同内容时,我得到了正确的JSON响应 . 它是一种hello.gz格式 . 这是字符编码的问题吗?
BÈ\u001Bå%\u0011Áfbâÿ|yÇoþ\u0019Y¤Zb\ u000E©¿zÆzùÝÖ½6\u001AÔ~ü\ u0019 \ u009B£IVY¯u¥\ u008B \ u0012 \ u0017f \ u> u u u u u u u u u u u u u 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 \ u009B \u0081MÆμ\ u001F«\ u0006 \ u0085vz \u001Deúz¬Í¤×AE \ u0010 \ u000E“{¡£/É¡Ò\u0090rHù\u0096¼\ u009C±立方厘米\ U0004 \ u000F÷BA°N \ u0081 \ u0002μÊ\u0087Ì,2£CHO \ U0001〜d \ u000BN?“>5ÀTvÔ\u001CÞC£\ u009F>Þ* LAE£Ú\ u008FC \u00831þªÀmÙuWÎ8ëý\ u0083` \u0086SñË\ u0099¢YC \ u000B \ u0018£÷NU 'è&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 回答
将
MediaType.APPLICATION_JSON_VALUE
替换为MediaType.APPLICATION_JSON_UTF8_VALUE
应该有效 .否则,尝试将带有UTF-8字符集的消息转换器添加到
RestTemplate
: