I've a small Java Apache HttpCore 4 based client class that makes calls to a service and I wanted to measure the response time of the http request/response round-trip. I thought there would be a way to read it from the HttpResponse object's meta data. But I was not able to get the response time in the response object. So, my solution was I stored the time before making a call then measured the time after making a call, and the difference is the elapsed time .
BasicHttpRequest request = new BasicHttpRequest("GET", target);
request.setParams(params);
httpexecutor.preProcess(request, httpproc, context);
long start = System.nanoTime();
HttpResponse httpResponse = httpexecutor.execute(request, conn, context);
long elapsed = System.nanoTime() - start;
System.out.println("Elapsed nano seconds -->" + elapsed);
httpResponse.setParams(params);
httpexecutor.postProcess(httpResponse, httpproc, context);
for eg, I get the following elapsed time: Elapsed time -->1561599815
And I could read the following headers with the following values from the response object, but I couldn't find anything related to response time:
| Server --> Apache-Coyote/1.1 |
| Date --> Mon, 26 Aug 2013 19:22:00 GMT |
| Content-Type --> application/json |
| Transfer-Encoding --> chunked |
The above solution is ugly specially in the asynchronous non-blocking code where I had to make callback function calls by anonymous inner function FutureCallback. like this:
requester.execute(new BasicAsyncRequestProducer(target, request),
new BasicAsyncResponseConsumer(), pool,
new BasicHttpContext(),
// Handle HTTP response from a callback
new FutureCallback<HttpResponse>() {
private int startTime; ...//etc
So this code is a not elegant. I wanted to get the response object to give me the elapsed time of http traffic. How can I do that?
I'm using httpClient 4.2, httpCore-nio 4.2, httpasyncclient 4.0 beta.
The response is sent from the server which received your request. So, the only time the server could send you is the time it needed for processing the request. But you are interested in the network traffic as well, so this approach will not be suitable for you anyway.
In the blocking i/o mode request execution (or processing) is terminated immediately after receiving a message head (request line + headers). Message body, when available, is associated with the content entity as an
InputStream
instance. This enables the consumer to stream the content directly from the underlying network socket. So, all you have to is to ensure that the response content entity is fully consumed.