使用OkHttp分析http请求

时间:2015-11-10 07:59:55

标签: 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();
}

3 个答案:

答案 0 :(得分:1)

Square here提供了一个日志记录拦截器的实现。它会记录总请求时间。它还会记录Ok-Http-SentOk-Http-Received标头。我不太了解实现细节,知道这些含义是什么,文档很少。

我还推荐Facebook的Stetho图书馆。它提供了一个相当详细的请求视图。特别是,它将跟踪"延迟"和"时间" (两者都没有与OkHttp日志记录提供的指标对齐)。他们的implementation拦截器也可以帮助你获得自己的日志记录机制。

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

答案 1 :(得分:1)

改为使用response.receivedResponseAtMillis()response.sentRequestAtMillis()

答案 2 :(得分:0)

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

plugin screenshot

https://github.com/itkacher/OkHttpProfiler

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

有关Charles设置https://link.medium.com/KU8QBMMRjR

的更多详细信息