使用 OkHttp 分析 http 请求

Mic*_*ael 6 android okhttp

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

我想得到:

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

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

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();
}
Run Code Online (Sandbox Code Playgroud)

Coa*_*ose 2

这里有 Square 提供的日志拦截器的实现。它确实记录了总请求时间。它还将记录Ok-Http-SentOk-Http-Received标头。我对实现细节了解不够,无法了解这些含义,而且文档也很少。

我还推荐 Facebook 的Stetho库。它提供了相当详细的请求视图。特别是,它将跟踪“延迟”和“时间”(两者都不符合 OkHttp 日志记录提供的指标)。他们的拦截器实现还可以帮助您导出自己的日志记录机制。

有一个悬而未决的stetho 问题,讨论添加更详细的信息,类似于在浏览器中执行查询(分析 dns 查找、ssl 握手等),但看起来它需要(重大?)对 OkHttp 进行修改才能可行。