RestTemplate encoding issue

5.8k views Asked by At

While getting data from one of web service quote(") is coming as (?) when i use Rest Template. I tested the web service in the postman on chrome and it giving correct characters. I tried encoding UTF-8, but no success.

I checked following are encoding from web service provider :

Cache-Control → private Connection → close Content-Encoding → gzip Content-Length → 3407 Content-Type → text/xml; charset=ISO-8859-1 Date → Wed, 10 Jun 2015 13:35:53 GMT Server → Google Search Appliance Vary → Accept-Encoding X-Frame-Options → SAMEORIGIN x-content-type-options → nosniff x-xss-protection → 1; mode=block

Here is my code :

RestTemplate restTemplate = new RestTemplate();

    HttpHeaders headers = new HttpHeaders();
    MediaType mediaType = new MediaType("text", "xml", Charset.forName("ISO-8859-1"));

    headers.set("Accept", "text/xml; charset=ISO-8859-1");
    headers.setContentType(mediaType);
    headers.setAcceptCharset(Arrays.asList(Charset.forName("UTF-8")));
    headers.setAccept(Arrays.asList(mediaType));

    ResponseEntity<String> res = restTemplate.exchange(gsaSearchUrl, HttpMethod.GET, new HttpEntity<String>(headers), String.class);


    System.out.println(res.getBody());
1

There are 1 answers

0
digby_the_snitch On

You need to add a HttpMessageConverter for UTF-8 encoded Strings to your RestTemplate. Something like this will do it for you:

    restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));