我在使用RestTemplate以UTF-8编码发布JSON时遇到问题。JSON的默认编码为UTF-8,因此媒体类型甚至不应包含字符集。我试图将charset放入MediaType中,但无论如何似乎都行不通。
我的代码:
String dataJson = "{\"food\": \"smörrebröd\"}"; HttpHeaders headers = new HttpHeaders(); MediaType mediaType = new MediaType("application", "json", StandardCharsets.UTF_8); headers.setContentType(mediaType); HttpEntity<String> entity = new HttpEntity<String>(dataJson, headers); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<Boolean> formEntity = restTemplate.exchange(postUrl, HttpMethod.POST, entity, Boolean.class);
您需要将StringHttpMessageConverter添加到具有字符集UTF-8的其余模板的消息转换器中。像这样
RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters() .add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));