Question

Can someone help with ideas how I can calculate amount of traffic(in/out).

I have app that gets API requests, each request stored in DB for statistic. I need store traffic size for each request and response.

From HttpServletRequest I can get size of request easily but how I can ger response size?

Also ProceedingJoinPoint used.

Was it helpful?

Solution

You can count the bytes written by wrapping the OutputStream used in HttpServletResponse (by wrapping the response as well)

public class CountingFilter implements Filter {

   public void doFilter(...) {
       chain.doFilter(request, new SizeCountingHttpServletResponse(response));
   }

   public static class SizeCountingHttpServletResponse extends HttpServletResponseWrapper {

      ....
      @Override
      public OutputStream getOutputStream() {
          return new CountingOutputStream(super.getOutputStream());
      }
      // same with getWriter()..
   }

   public static class CountingOuputStream extends OutputStream {
       private int size;
       // delegate all methods to the original OutputStream
       // count the number of byte written and store in the 'size' field.
   }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top