使用OkHttp分析http请求 [英] Profiling http request with OkHttp

查看:90
本文介绍了使用OkHttp分析http请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用OkHttp跟踪详细的请求时间.

How to track detailed request time with OkHttp.

我想得到:

  • 连接时间;
  • 发送时间;
  • 接收时间;

我尝试使用拦截器机制,但是它仅提供总请求时间.

I tried to use Interceptors mechanism, but it provides only total request time.

class LoggingInterceptor implements Interceptor {
  @Override public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();

    long t1 = System.nanoTime();
    logger.info(String.format("Sending request %s on %s%n%s",
        request.url(), chain.connection(), request.headers()));

    Response response = chain.proceed(request);

    long t2 = System.nanoTime();
    logger.info(String.format("Received response for %s in %.1fms%n%s",
        response.request().url(), (t2 - t1) / 1e6d, response.headers()));

    return response;
  }
}

// sample request
String post(String url, String json) throws IOException {

  MediaType JSON = MediaType.parse("application/json; charset=utf-8");
  OkHttpClient client = new OkHttpClient();
  client.networkInterceptors().add(new LoggingInterceptor());

  RequestBody body = RequestBody.create(JSON, json);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}

推荐答案

Square提供了一个日志拦截器的实现

There is an implementation of a logging interceptor provided by Square here. It does log the total request time. It also will log the Ok-Http-Sent and Ok-Http-Received headers. I do not know enough of the implementation details to know what those mean, and the documentation is sparse.

我还建议使用Facebook的 Stetho 库.它提供了合理详细的请求视图.特别是,它将跟踪等待时间"和时间"(二者均与OkHttp日志记录所提供的度量标准不符).他们的拦截器的实现还可以帮助您导出自己的日志记录机制.

I also recommend Facebook's Stetho library. It provides a reasonably detailed view of requests. In particular, it will track "latency" and "time" (neither of which line up with the metrics provided by OkHttp logging). Their implementation of the interceptor may also help you derive your own logging mechanism.

有一个尚待解决的 stetho问题,该问题讨论添加更详细的信息,类似于执行浏览器中的查询(分析dns查找,ssl握手等),但是在可行之前,它似乎需要(显着吗?)对OkHttp进行修改.

There is a pending stetho issue that discusses adding more detailed information, similar to executing a query in the browser (profiling dns lookup, ssl handshaking, etc), however it looks like it requires (significant?) modifications to OkHttp before being viable.

这篇关于使用OkHttp分析http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆