简体   繁体   English

Java Spring RestTemplate字符编码问题

[英]Issues with Java Spring resttemplate character encoding

I'm using the Java Spring Resttemplate for getting a json via a get request. 我正在使用Java Spring Resttemplate通过get请求获取json。 The JSON I'm getting has instead of special character slike ü ö ä or ß some weird stuff. 我得到的JSON代替了诸如üöä或ß之类的特殊字符。 So I guess somethings wrong with the character encoding. 所以我猜字符编码有问题。 I can't find any help on the internet. 我在互联网上找不到任何帮助。 The code I'm using for now is: 我现在使用的代码是:

        String json = restTemplate.getForObject(
        overPassStatementPostCode,
        String.class,
        params);

The overPassStamementPostCode is just a string with placeholders. overPassStamementPostCode只是一个带有占位符的字符串。 It gets filled with the parameters in the params Map. 它被参数映射中的参数填充。

The problem is that the String json doesn't have the wanted encoding. 问题是String json没有所需的编码。

Thank you for the help. 感谢您的帮助。 Best regards Daniel 最好的问候丹尼尔

Have you tried setting an encoding filter in web.xml? 您是否尝试过在web.xml中设置编码过滤器?

<filter>
 <filter-name>encodingFilter</filter-name>
 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
 <init-param>
     <param-name>encoding</param-name>
    <param-value>UTF-8</param-value>
 </init-param>
 <init-param>
     <param-name>forceEncoding</param-name>
     <param-value>true</param-value>
 </init-param>
</filter>
<filter-mapping>
 <filter-name>encodingFilter</filter-name>
 <url-pattern>/*</url-pattern>
</filter-mapping>

You can set the encoding in HttpHeaders . 您可以在HttpHeaders设置编码。 Below code could help you: 下面的代码可以帮助您:

HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.set("Accept", "text/html;charset=utf-8");

HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);

RestTemplate template = new RestTemplate();
ResponseEntity<String> response = template.exchange(
                "http://localhost/hello", HttpMethod.GET, requestEntity,
                String.class);

Specify a converter that can convert from and to HTTP requests and responses. 指定一个可以与HTTP请求和响应之间进行转换的转换器。 Here is an example. 这是一个例子。

RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM