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

梦想的初衷 提交于 2019-12-01 01:05:25

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");

You can use them both, just not at the same time, or rather not for the same response. If you need to use a Writer after you've already started using the OutputStream, just wrap an OutputStreamWriter around the output stream. However if you need to use an output stream after you've already used the writer you can't. You could always get the output stream first, wrap the writer around it as above, do your Writing, flush, then do your output streaming.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!