Change encoding of HttpServletResponse

I found that you MUST set the character encoding to at least UTF-8 because the default is ISO-8859-1. The ISO-8859-1 character set doesn't account for some extended characters. I wrote a helper function to use what is sent in the "Accept" header:

public static void setResponseCharacterSet(HttpServletRequest request, HttpServletResponse response)
{
    String type = "UTF-8";
    if(request.getHeader("accept") != null)
    {
        String[] params = request.getHeader("accept").split("charset=");
        if(params.length == 2) {
            type = params[1];
        }
    }
    response.setCharacterEncoding(type);
}

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.


First

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

Then, make sure you're actually emitting that encoding!


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(); ...!