Shachty
Shachty

Reputation: 561

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

Upvotes: 2

Views: 11938

Answers (4)

Bhukailas
Bhukailas

Reputation: 57

Upgrading to spring-web 5.2 solves the problem. or set writeAcceptCharset property to false belongs to StringHttpMessageConverter and use that convertor further in RestTemplate instance.

boolean writeAcceptCharSet = false;
List<HttpMessageConverter<?>> c = restTemplate.getMessageConverters();
for (HttpMessageConverter<?> mc : c) {
  if (mc instanceof StringHttpMessageConverter) {
    StringHttpMessageConverter mcc = (StringHttpMessageConverter) mc;
    mcc.setWriteAcceptCharset(writeAcceptCharSet);
  }
}

Upvotes: 0

Nelson
Nelson

Reputation: 59

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));

Upvotes: 0

Mithun
Mithun

Reputation: 8067

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);

Upvotes: 1

Stefan
Stefan

Reputation: 12463

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>

Upvotes: 0

Related Questions