3

I want monitor the response size in a servlet, so I plan to add filter to implement this function.

But I don't know how to get the response size when I check HttpServletResponse methods:

response.getWriter()
response.getOutputStream()

Is there any efficient way to calculate the total response size?

Sean Bright
  • 118,630
  • 17
  • 138
  • 146
Bensson
  • 4,509
  • 4
  • 19
  • 24

5 Answers5

3

If you have access to the response header, you can read the Content-Length. For example,

(Status-Line):HTTP/1.1 200 OK
Connection:Keep-Alive
Date:Fri, 10 Mar 2015 14:00:00 GMT
Content-Length:728
Faraz
  • 6,025
  • 5
  • 31
  • 88
  • Thanks for you reply. I just do some debug, and only can get 3 header. Content-Type|Transfer-Encoding|Date. Cannot find Content-Length in HttpServletResponse. – Bensson Jan 19 '17 at 14:42
  • @Bensson: if neither you servlet nor any filter add the field it cannot be present in the response. – Serge Ballesta Jan 19 '17 at 14:44
  • @SergeBallesta The same as you said, but content-length did not automatic update with the actual size. – Bensson Jan 19 '17 at 15:10
2

You could use a Filter to provide the servlet with a HttpServletResponseWrapper which would override getWriter and getOutputStream. Both method would return wrappers to actual streams that count the characters written there.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
1

You don't have to do the monitoring of such basic HTTP stuff yourself, Tomcat does it for you:

Add the AccessLogValve to your server.xml and voila you have the response size given by the %b variable in the access logs.

gsl
  • 676
  • 5
  • 16
  • Thx, Actually i want control this per user, so that I want process this in filter. it's really hard doing this in AccessLogValve . – Bensson Jan 20 '17 at 01:12
1

Reflection FTW.

    public static Long getByteCount(final HttpServletResponse response) {
    try {
        Field innerResponseField = ServletResponseWrapper.class.getDeclaredField("response");
        innerResponseField.setAccessible(true);
        innerResponseField.get(response);
        Object innerResponse = innerResponseField.get(response);
        Field contentWrittenField = OnCommittedResponseWrapper.class.getDeclaredField("contentWritten");
        contentWrittenField.setAccessible(true);
        return (Long) contentWrittenField.get(innerResponse);
    } catch (Exception e) {
        return null;
    }
}
Pete Terlep
  • 191
  • 1
  • 10
0

There is no way to get total size of HttpServletRequest using JavaEE API.

Alexei Petrov
  • 331
  • 5
  • 14