1

I'm using an interceptor that will intercept before and after the request. The purpose of this is to get the size of the content sent and returned, however, I do not know of a way to get the answer, it seems that the response does not have a method to get it.

@Component
public class DataUsageInterceptor extends HandlerInterceptorAdapter {

    private static final Logger LOG = LoggerFactory.getLogger(CheckController.class);

    @Override
    public boolean preHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler
    ) throws Exception {

        System.out.println("---- " + request.getContentLength() + "----------");

        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler, Exception ex
    ) throws Exception {

        System.out.println("---------- get length here ----------------");

    }
}
Jonathan
  • 127
  • 1
  • 8
  • 1
    Possible duplicate of [Determine size of HTTP Response?](https://stackoverflow.com/questions/5435351/determine-size-of-http-response) – Dherik Jan 30 '18 at 10:35

1 Answers1

2

I think you can get content size from response headers. It's will seems something like that:

response.getHeader("Content-Length");

For reference:

https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletResponse.html#getHeader(java.lang.String)

https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html (Section - 14.13 Content-Length)

  • 5
    Please mind that server will not always attach `Content-Length` header in the response. See also `Transfer-Encoding: chunked` – diginoise Jan 30 '18 at 11:04
  • @diginoise Hello, the return comes the field: `Transfer-Encoding: chunked`. How to change? – Jonathan Jan 30 '18 at 12:01
  • @Jonathan this is attached by the server... if you control the server and you can build the entire body of the response up, then you can measure its size. It will cost you time (the response arrives later to the client). If however you can't modify the server OR you are genuinely streaming the response (imagine it's a video stream of a webcam or a temperature readings from an on-line thermometer) then this is it I am afraid. – diginoise Jan 30 '18 at 12:14