Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change encoding of HttpServletResponse

I have an API that returns XML, it actually returns it using the default encoding (I believe it's UTF-8), but now requirements have changed and we need to return everything in UTF-16LE.

My question is: is there an easy way of doing this? I have access to the response just before the calls complete so I was wondering if I could do something like

//This method does not exist
response.setCharacterEncoding("UTF-16LE");

Thanks a lot!

UPDATE: The method mentioned is the one to use. I was using an old version (2.3) of the servlet API that did not include it. Changing the version fixed it all.

like image 795
Pablo Fernandez Avatar asked Dec 04 '09 19:12

Pablo Fernandez


2 Answers

Uhh, the method does exist, here

Sets the character encoding (MIME charset) of the response being sent to the client, for example, to UTF-8. If the character encoding has already been set by setContentType(java.lang.String) or setLocale(java.util.Locale), this method overrides it. Calling setContentType(java.lang.String) with the String of text/html and calling this method with the String of UTF-8 is equivalent with calling setContentType with the String of text/html; charset=UTF-8.

like image 119
skaffman Avatar answered Sep 17 '22 16:09

skaffman


As others have stated, use either:

response.setCharacterEncoding("UTF-16LE");

or:

response.setHeader("Content-Type", "text/xml; charset=UTF-16LE");

...but make sure you do this before calling response.getWriter(); ...!

like image 31
Tim Cooper Avatar answered Sep 20 '22 16:09

Tim Cooper