简体   繁体   中英

Count actual bytes written to tomcat HttpServletResponse

I need to count the actual bytes written to a HttpServletResponse to make sure that the whole file has been transfered. My naive approach is like this:

            InputStream instream = InputStream instream = new FileInputStream("myfile.zip");
            ServletOutputStream outputStream = res.getOutputStream();

            CountingInputStream countingInputStream = new CountingInputStream(instream);
            IOUtils.copy(countingInputStream, outputStream);

            log.debug("Expected count: " + String.valueOf(contentLength));
            log.debug("getCount: " + countingInputStream.getCount());

            outputStream.close();
            countingInputStream.close();
            instream.close();

While this approach works well on Jetty, Tomcat returns always the full outputstream to be written, even if the client has canceled the download.

Futhermore this has also worked well for years on Tomcat 6. We now had to migrate to Tomcat 7 and experienced this issue.

Is there a way to count the bytes that have been actually sent to the client?

There are several things that you have to investigate:

  1. Is the content length header provided? If not, tomcat will cache the entire response
  2. Make sure the container is configured to support chunked encoding.
  3. Make sure the client supports chunked encoding (it is not HTTP 1.0)

Another thing is that the tomcat streaming infrastructure suffered a major refactoring with the websockets implementation after version 7.0.27. For more details, take a look here:

http://www.tomcatexpert.com/blog/2012/05/01/how-apache-tomcat-implemented-websocket

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM