Reputation: 42176
I'm using App Engine's Maven plugin to deploy a simple servlet:
package test;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/test")
public class TestServlet extends HttpServlet{
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setContentType("application/json");
String output = "testing ¡ ¿ ñ testing";
response.getOutputStream().println(output);
}
}
This servlet outputs some text that includes special characters like ¡
, ¿
, and ñ
.
I run a local development server: mvn appengine:devserver
And I navigate to http://localhost:8080/test
. I see this:
testing � � � testing
I gather that these are replacement characters and indicate that something is wrong with my encoding.
I've tried specifically setting the charset:
response.setContentType("application/json; charset=UTF-8");
I've also tried:
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
I've confirmed that the browser is getting this character encoding in the headers of the response:
But I still see the replacement characters instead of the original special characters.
If I deploy to a live App Engine site, then it works fine and the original special characters are shown. I see that the live site has a content-encoding
of gzip
, but this might be a red herring:
I've tried this on both Windows and Linux, and I'm getting the same behavior on both.
How do I set the encoding of my local development server so I can see the original special characters instead of the replacement characters?
Upvotes: 1
Views: 70
Reputation: 42176
Turns out I needed to call response.getWriter().println(output)
instead of response.getOutputStream().println(output)
.
From the JavaDoc for HttpServletResponse
:
getOutputStream()
returns a ServletOutputStream
suitable for writing binary data in the response. The servlet container does not encode the binary data.
getWriter()
returns a PrintWriter
object that can send character text to the client. The PrintWriter
uses the character encoding returned by getCharacterEncoding()
.
Upvotes: 1