Reputation: 2283
getting an IOExcepiton on the PrintWriter when doing this in doPost method of servlet class:
doPost(HttpServletRequest request,
HttpServletResponse response){
String replyMessage = "STATUS_ACCEPT";
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("text/plain; charset=utf-8");
response.setContentLength(replyMessage.length());
response.setIntHeader("content-length", replyMessage.length());
response.getWriter().println(replyMessage);//getting IOException closed on calling this method
response.flushBuffer();}
If I use the outputstream for sending data there is no error:
ServletOutputStream outputStream = response.getOutputStream();
byte[] result = "STATUS_ACCEPT".getBytes("UTF-8");
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("text/plain; charset=utf-8");
response.setContentLength(result.length);
response.setIntHeader("content-length", result.length);
outputStream.write(httpOutData);
how should i use the printwriter for not getting the IOException?
Upvotes: 1
Views: 1523
Reputation: 66263
Most like the reason is this:
response.setContentLength(replyMessage.length());
// ...
response.getWriter().println(replyMessage)
Which means, that your response content is at least one byte longer than announced by setContentLenght
: The trailing newline appended by println()
. Perhaps the difference is two bytes: CR and LF.
Note: If you fix this you will still have problems in the general case: You set the content length to the number of characters which in UTF-8 encoding is not always the number of bytes. setContentLength()
wants the number of bytes.
Therefore it would be better to simply delete all code fiddling with the content-length because if you don't set it, it will be calculated automatically.
Upvotes: 4
Reputation: 33544
PrintWriter pw = response.getWriter();
pw.println("hello"); // flush is not required here....
Upvotes: 1