使用 OkHttp 分析 http 请求

Profiling http request with 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();
}

Square here 提供了一个日志拦截器的实现。它确实记录了总请求时间。它还将记录 Ok-Http-SentOk-Http-Received headers。我对实现细节的了解还不够多,无法理解它们的含义,而且文档也很少。

我也推荐 Facebook 的 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 的拦截器,也可以帮助您推导出自己的日志记录机制。

有一个待处理的 stetho issue 讨论添加更详细的信息,类似于在浏览器中执行查询(分析 dns 查找、ssl 握手等),但它看起来需要(重要?)在可行之前对 OkHttp 进行修改。

  1. 您可以在Android工作室
  2. 中直接使用OkHttp Profiler插件调试请求

https://github.com/itkacher/OkHttpProfiler

  1. 您可以使用 Charles 代理应用程序

有关 Charles 设置的更多详细信息https://link.medium.com/KU8QBMMRjR

使用response.receivedResponseAtMillis()response.sentRequestAtMillis()代替