关于PrintWriter的flush()步骤
阅读
在web编程中需要返回数据给客户端时都是采用PrintWriter,获取一个输出流对象采用以下方法!奇怪的是当调用了flush()方法后,会在返回的数前面加上一个以16进制表示的数据大小,以及最后面加个0,请问这是怎么回事?谁给我解释下!做这客户端那边的老大给我下难题了,要我给他个合理解释为什么会这样!
- Java code
response.setContentType("text/xml"); response.setCharacterEncoding("utf-8"); PrintWriter out=null; try { out=response.getWriter(); msg.append("<data>"); msg.append(sbf.toString()); msg.append("</data>"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } out.print(msg.toString()); out.flush();//加上这个就会在数据前自动加上大小及最后一个0 out.close();
------解决方案--------------------
你说的数据是什么,是msg吗?
调用flush()之后会加东西?那去掉呢,后面直接跟着out.close()也就写文件了,不用flush也一样。
------解决方案--------------------
这么神奇?
你用response.setContentType("text/html");一定可以。
------解决方案--------------------
你如果用了response.getWriter().flush()方法,容器的实现会认为你要输出的内容无法确定大小(因为你已经先flush先输出一部分内容了),所以就采用了chunked编码方式输出。
chunked编码一般按照下面类似的方式输出。
chunk #1(这里通常是16进制的数字,标志这个块的大小)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"....
chunk #2
<div .....
chunk #3
....</body></html>
0(全部输出结束用0)
你可以注意看一下返回的内容。如果你不用flush,那么返回的http头里是包含 Content-Length: xxx 这样的,表示返回的全文长度。
如果用了flush(),那么就没有Content-Length: xxx, 而是多了一个 Transfer-Encoding: chunked,表示分段输出。
------解决方案--------------------
- HTML code
HTTP/1.1 200 OK Date: Wed, 27 Jun 2012 05:26:51 GMT Server: Apache/2.2.22 (FreeBSD) PHP/5.2.6 with Suhosin-Patch mod_ssl/2.2.22 OpenSSL/0.9.7e-p1 X-Powered-By: PHP/5.2.6 Cache-Control: private, must-revalidate, max-age=0, proxy-revalidate, no-transform Pragma: no-cache Vary: Accept-Encoding Connection: close Transfer-Encoding: chunked Content-Type: text/html [color=#FF0000]321e[/color] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!--[71,88,7] published at 2012-06-19 16:22:21 from #187 by 6050--> <!doctype html> <html> <head>阅读上一篇:s:form 出现找不到action的有关问题 下一篇:返回列表