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.

About these ads

About ChandanPandey

Try to come up with a good design as by product of good coding practices

Posted on January 8, 2013, in Java, Spring, Spring Integration and tagged , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 32 other followers

%d bloggers like this: