我有responseEntity
喜欢这个:
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
requestHeaders.setContentType(MediaType.valueOf("text/plain;charset=UTF-8"));
HttpEntity requestEntity = new HttpEntity(jsonQuery, requestHeaders);
ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
//Not in UTF-8!!
logger.debug("result: " + responseEntity.getBody());
但它没有在UTF-8
中编码,并产生如下字符:Soci굩
。是否可以在UTF-8
中创建或在restTemplate中以某种方式添加编码?
答案 0 :(得分:6)
requestHeaders .add("Content-Type", "text/html; charset=utf-8");
答案 1 :(得分:1)
解决方案是在StringHttpMessageConverter
bean中添加utf-8
restTemplate
,如:
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters()
.add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
return restTemplate;
}
答案 2 :(得分:1)
我只需将 charset = utf8 添加到我的RequestMapping中即可解决相同的问题。
之前
@RequestMapping(path = "/{id}", method = RequestMethod.GET, produces = "application/hal+json")
之后
@RequestMapping(path = "/{id}", method = RequestMethod.GET, produces = "application/hal+json;charset=utf8")
我也将此添加到其他方法中。希望对您有所帮助。
答案 3 :(得分:0)
我已经解决了这个问题。我需要使用UTF-8在请求正文中发布一个字符串对象。
文本/纯文本
httpHeaders.setContentType(new MediaType(“ text”,“ plain”,StandardCharsets.UTF_8));
applicaton / json
httpHeaders.setContentType(new MediaType(“ applicaton”,“ json”,StandardCharsets.UTF_8));
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> resposeEntity = null;
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(new MediaType("text", "plain", StandardCharsets.UTF_8));
HttpEntity<String> httpEntity = new HttpEntity<String>(stringContent, httpHeaders);
responseEntity = restTemplate.exchange(requestUrl, HttpMethod.POST, httpEntity, String.class);
if (HttpStatus.OK.equals(responseEntity.getStatusCode())) {
logger.debug("... success ... result: " + responseEntity.getBody());
}
答案 4 :(得分:0)
替代方法:
我们知道默认情况下,import data from './assets/woerter.json';
StringHttpMessageConverter将为ISO-8859-1,因此我们可以像这样将响应转换为UTF-8。
RestTemplate