简体   繁体   中英

Issues with Java Spring resttemplate character encoding

I'm using the Java Spring Resttemplate for getting a json via a get request. The JSON I'm getting has instead of special character slike ü ö ä or ß some weird stuff. 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. It gets filled with the parameters in the params Map.

The problem is that the String json doesn't have the wanted encoding.

Thank you for the help. Best regards Daniel

Have you tried setting an encoding filter in 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 . 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. Here is an example.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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