[英]HttpCore for measuring http request/response elapsed time
我有一个基于Java Apache HttpCore 4的小型客户端类,该客户端类对服务进行了调用,我想测量http请求/响应往返的响应时间。 我认为会有一种方法可以从HttpResponse对象的元数据中读取它。 但是我无法在响应对象中获得响应时间。 因此,我的解决方案是我存储了拨打电话之前的时间,然后测量了拨打电话之后的时间,所不同的是经过的时间。
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);
例如,我得到以下经过时间:经过时间-> 1561599815
我可以从响应对象中读取具有以下值的以下标头,但找不到与响应时间有关的任何内容:
| Server --> Apache-Coyote/1.1 |
| Date --> Mon, 26 Aug 2013 19:22:00 GMT |
| Content-Type --> application/json |
| Transfer-Encoding --> chunked |
上面的解决方案在异步非阻塞代码中特别难看,在该代码中,我必须通过匿名内部函数FutureCallback进行回调函数调用。 像这样:
requester.execute(new BasicAsyncRequestProducer(target, request),
new BasicAsyncResponseConsumer(), pool,
new BasicHttpContext(),
// Handle HTTP response from a callback
new FutureCallback<HttpResponse>() {
private int startTime; ...//etc
因此,这段代码并不完美。 我想获取响应对象,以提供HTTP流量经过的时间。 我怎样才能做到这一点?
我正在使用httpClient 4.2,httpCore-nio 4.2,httpasyncclient 4.0 beta。
在阻塞I / O模式中,请求执行(或处理)在接收到消息头(请求行+标头)后立即终止。 消息正文(如果可用)与内容实体相关联,作为InputStream
实例。 这使使用者可以直接从底层网络套接字流式传输内容。 因此,您要做的就是确保响应内容实体被完全消耗。
long start = System.nanoTime();
HttpResponse httpResponse = httpexecutor.execute(request, conn, context);
EntityUtils.consume(httpResponse.getEntity());
long elapsed = System.nanoTime() - start;
因此,这段代码并不完美。 我想获取响应对象,以提供HTTP流量经过的时间。 我怎样才能做到这一点?
响应是从接收您请求的服务器发送的。 因此,服务器唯一可以发送给您的时间就是处理请求所需的时间。 但是您也对网络流量感兴趣,因此无论如何该方法都不适合您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.