Search code examples
javaapache-httpcomponents

Measure bandwidth usage with Apache HttpComponents HttpClient


How can I measure HttpClients bandwidth usage for my app? (HttpComponents 4.3)

I have a client application that is communicating with a server using HttpClient. All requests are done through the same client using a pooling http connection manager. Unfortunately, most of the requests use the httpclient directly (not all of them) so measuring bandwidth at the request location would be doable, but a pain.

Is there a place at either the constructor of the client or the connection manager where I can simply inject my own bandwidth monitor (or is that already built in somewhere that I haven't discovered)?

Can I do it with this?

    HttpClientBuilder.create().addInterceptorLast(new HttpResponseInterceptor()
    {

        @Override
        public void process(HttpResponse response, HttpContext context) throws HttpException, IOException
        {

        }
    }).build();

Solution

  • Custom HttpRequestExecutor should probably the most convenient interception point

    This is a very crude solution but I hope is enough to get you started.

    final AtomicLong totalBytes = new AtomicLong();
    
    HttpRequestExecutor requestExecutor = new HttpRequestExecutor() {
    
        @Override
        protected HttpResponse doSendRequest(
                final HttpRequest request,
                final HttpClientConnection conn,
                final HttpContext context) throws IOException, HttpException {
            HttpResponse response = super.doSendRequest(request, conn, context);
            HttpConnectionMetrics metrics = conn.getMetrics();
            totalBytes.addAndGet(metrics.getSentBytesCount());
            metrics.reset();
            return response;
        }
    
        @Override
        protected HttpResponse doReceiveResponse(
                final HttpRequest request,
                final HttpClientConnection conn,
                final HttpContext context) throws HttpException, IOException {
            HttpResponse response = super.doReceiveResponse(request, conn, context);
            HttpConnectionMetrics metrics = conn.getMetrics();
            totalBytes.addAndGet(metrics.getReceivedBytesCount());
            metrics.reset();
            return response;
        }
    };
    
    CloseableHttpClient httpclient = HttpClients
            .custom()
            .setRequestExecutor(requestExecutor)
            .build();