Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use getOutputStream() and getWriter() in the same servlet request?

How do I use getOutputStream() and getWriter() in the same servlet request?

like image 498
Parith Avatar asked Nov 23 '25 09:11

Parith


1 Answers

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");
like image 138
Martin Algesten Avatar answered Nov 24 '25 23:11

Martin Algesten



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!