Friday, 22 September 2017

grails - UTF-8 encoded characters from REST-query not rendered properly



I'm consuming an external REST service that provides all content as UTF-8 encoded.



For some reason my application cannot properly handle the response. If I dump the response I will se things like LuleÃ¥ (should be Luleå).



EDIT:
The same behavior happens if i forward (without altering) the string to the UI, ex.:



flash.message = "Test" + integrationService.testEncoding()


What I did was to create a _Events.groovy file in the /script folder and specifying there that



eventConfigureTomcat = { tomcat ->
tomcat.connector.URIEncoding = "UTF-8"
tomcat.connector.useBodyEncodingForURI = true
}


I also have the following in my Config.groovy:



grails.views.gsp.encoding = "UTF-8"
grails.converters.encoding = "UTF-8"


But that changed nothing. The response is still wrongly shown. I'm not sure if this is a configuration issue with Grails, with the embedded tomcat or with something else. I'm currently running my test setup on windows 7, but the same issue happens on my server running on Centos. Please advice.



EDIT2:
If i consume the REST service using curl, everything is rendered correctly in the output.



EDIT3:
I'm using org.springframework.web.client.RestTemplate and HttpComponents to consume the service:



private static final HttpHeaders requestHeaders
static{
requestHeaders = new HttpHeaders()
requestHeaders.set(HttpHeaders.CONTENT_TYPE, "application/json")
requestHeaders.set(HttpHeaders.ACCEPT, "application/json")
requestHeaders.set("Accept-Encoding", "gzip")
}

private final static RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(
HttpClientBuilder.create().build()))
...
...
public def testEncoding(){
ResponseEntity response = restTemplate.exchange(
"https://www.url.com", HttpMethod.GET, new HttpEntity(requestHeaders),
String.class)
def gamesJson = JSON.parse(response.getBody())
//...
//parse value from gamesJson
//...
return testValue
}

Answer



Per my previous answer:



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 response = template.exchange(endpoint, method, entity,
Object.class);

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...