Miguel Ribeiro
Miguel Ribeiro

Reputation: 8184

charset encoding Tomcat Windows / JBoss Linux

I have 2 servers: 1 Tomcat 6 in windows and one JBoss 5 in linux.

When writing JSON (applicatio/json) to ouputstream I get special characters (Á,á, etc..) right in Tomcat but wrong in JBoss.

This is how I right to the output stream:

protected void writeToOutputStream(String response, String tag) {
    ServletOutputStream outputStream = null;
    try {
        logInfo("Writing to output stream");
        outputStream = httpresponse.getOutputStream();
        outputStream.write(response.getBytes(), 0, response.getBytes().length);
        outputStream.flush();
    } catch (IOException ex) {
        logError("Could not write response into output stream", ex);
    } finally {
        try {
            outputStream.close();
        } catch (IOException ex) {}
    }
}

If I force the charset with

httpresponse.setCharacterEncoding("utf-8");

It gets ok in JBoss but not in tomcat...

Any idea how to solve this?

Upvotes: 0

Views: 736

Answers (1)

Bruno Grieder
Bruno Grieder

Reputation: 29824

response.getBytes() uses the platform default encoding to convert String to bytes and the encodings are very likely not the same on your Windows (CP-1252) and Linux machine (utf-8).

You should pass to getBytes() the encoding (preferably 'utf-8' ) which must be identical to the one specified as the charsetin your content-type response header (utf-8 in your code above).

As a side note, the way you write to the Outpustream and the double call to getBytes() is quite inefficient. If you want to keep your code small yet efficient, use Apache commons-io and utilities like IOUtils.copy() to manipulate streams.

Upvotes: 1

Related Questions