How do I use getOutputStream() and getWriter() in the same servlet request?
You can't use them both at the same time. If you first did getOutputStream()
you can't consequently in the same request do getWriter()
and vice versa. You can however wrap your ServletOuptputStream
in a PrintWriter
to get the same kind of writer you would have from getWriter()
.
ServletOutputStream out = response.getOutputStream();
// Notice encoding here, very important that it matches that of
// response.setCharacterEncoding();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(out, "utf-8"));
Another solution to not using getWriter()
is to use a PrintStream
which is somewhat similar, but then you don't have type compatibility with Writer
or PrintWriter
.
// Encoding again very important to match that of your output.
PrintStream print = new PrintStream(os, true, "utf-8");