如何在android中获取HTTP请求/响应时序

时间:2018-01-18 07:26:45

标签: android okhttp

我需要记录这些:

  1. DNS时间
  2. 连接时间
  3. SSL时间
  4. 设备网络带宽
  5. 第一个字节时间
  6. 转移时间
  7. 没有对象/没有字节
  8. 我正在使用OKHttp库进行网络请求。

3 个答案:

答案 0 :(得分:1)

看看OkHttp的新EventListener:https://github.com/square/okhttp/wiki/Events

它提供了一种方法来将监听器连接到hcian的每一步,因此您可以获得如下信息:

class PrintingEventListener extends EventListener {
  private long callStartNanos;

  private void printEvent(String name) {
    long nowNanos = System.nanoTime();
    if (name.equals("callStart")) {
      callStartNanos = nowNanos;
    }
    long elapsedNanos = nowNanos - callStartNanos;
    System.out.printf("%.3f %s%n", elapsedNanos / 1000000000d, name);
  }

  @Override public void callStart(Call call) {
    printEvent("callStart");
  }

  @Override public void callEnd(Call call) {
    printEvent("callEnd");
  }

  @Override public void dnsStart(Call call, String domainName) {
    printEvent("dnsStart");
  }

  @Override public void dnsEnd(Call call, String domainName, List<InetAddress> inetAddressList) {
    printEvent("dnsEnd");
  }

  ...
}

你把它连接起来:

Request request = new Request.Builder()
    .url("https://publicobject.com/helloworld.txt")
    .build();

System.out.println("REQUEST 1 (new connection)");
try (Response response = client.newCall(request).execute()) {
  // Consume and discard the response body.
  response.body().source().readByteString();
}

将输出以下内容:

REQUEST 1 (new connection)
0.000 callStart
0.010 dnsStart
0.017 dnsEnd
0.025 connectStart
0.117 secureConnectStart
0.586 secureConnectEnd
0.586 connectEnd
0.587 connectionAcquired
0.588 requestHeadersStart
0.590 requestHeadersEnd
0.591 responseHeadersStart
0.675 responseHeadersEnd
0.676 responseBodyStart
0.679 responseBodyEnd
0.679 connectionReleased
0.680 callEnd

答案 1 :(得分:0)

如前所述,您正在使用OKHttp库进行HTTP调用,OKHttp库提供了使用logging-interceptor依赖项打印所需的每个API调用日志的工具。

您可以在以下链接中获得更多详细信息,并按照以下链接的步骤操作。 https://www.learn2crack.com/2016/06/retrofit-okhttp-logging-interceptor.html

答案 2 :(得分:0)

添加HttpLoggingInterceptor.It记录总请求时间。它还将记录Ok-Http-Sent和Ok-Http-Received标头。

public static Retrofit getInstance() {
if (instance == null) {
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();          
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();           
    httpClient.addInterceptor(logging);  // <-- this is the important line!
    instance = new Retrofit.Builder().baseUrl(Constant.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(httpClient.build())
                .build();
}
return instance;
}

并添加以下依赖项:

compile "com.squareup.okhttp3:logging-interceptor:3.3.1"