Java Spring resttemplate character encoding

Shachty picture Shachty · Dec 22, 2014 · Viewed 51k times · Source

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

Answer

beerbajay picture beerbajay · Feb 26, 2015

You just need to add the StringHttpMessageConverter to the template's message converters:

RestTemplate template = new RestTemplate();
template.getMessageConverters()
        .add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
ResponseEntity<Object> response = template.exchange(endpoint, method, entity, 
                                                    Object.class);