Blog Archives

Solving character encoding issue with Spring REST


While working on one of spring integration project, we fetched an XML using REST service and while we dumped it, we observed that many of characters were jumbled -which means encoding setting was screwed up. Spring integration configuration code

<int-http:outbound-gateway request-channel="testChannel"
		url="${test.url}" http-method="GET" expected-response-type="java.lang.String"
		reply-channel="glHeaderEnricher" charset="iso-8859-1">
		<int-http:uri-variable name="site_code"
			expression="payload" />
	</int-http:outbound-gateway>

As above mentioned, we were setting the expected char set as well.
“http:outbound-gateway” from Spring is nothing but a wrapper around Spring REST template, so started investigating what going on with REST template. REST template has option to inject message converters, by default converters which get registered are ByteArrayHttpMessageConverter, StringHttpMessageConverter, and ResourceHttpMessageConverter.

In spring integration configuration we had set “expected-response-type=”java.lang.String”” was causing StringHttpMessageConverter to be selected and used, and hence even before the XML payload reached our system it had lost it’s encoding.

Solution? using ByteArrayHttpMessageConverter, which can be done by setting

<int-http:outbound-gateway request-channel="testChannel"
		url="${test.url}" http-method="GET" expected-response-type="byte[]"
		reply-channel="glHeaderEnricher" charset="iso-8859-1">
		<int-http:uri-variable name="site_code"
			expression="payload" />
</int-http:outbound-gateway>

Once read as a raw byte it can be converted to string in any encoding.

Advertisements