Reputation: 2150
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();
Upvotes: 2
Views: 1838
Reputation: 31
HttpClient client = HttpClients.createDefault();
HttpGet req = new HttpGet("https://www.google.com/");
HttpClientContext hcc = HttpClientContext.create();
HttpResponse res = client.execute(req, hcc);
HttpConnectionMetrics metrics = hcc.getConnection().getMetrics();
EntityUtils.consumeQuietly(res.getEntity());
LOG.debug("sent: {}, recv: {}, reqcnt: {}, rescnt: {}",
metrics.getSentBytesCount(), metrics.getReceivedBytesCount(),
metrics.getRequestCount(), metrics.getResponseCount());
HttpConnectionMetrics hold everything you need.
Upvotes: 1
Reputation: 27548
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();
Upvotes: 7