如何在安卓中获取HTTP请求/响应时间

3

我需要记录以下内容:

  1. DNS时间
  2. 连接时间
  3. SSL时间
  4. 设备网络带宽
  5. 首字节时间
  6. 传输时间
  7. 对象数量/字节数量

我正在使用OKHttp库进行网络请求。


点击这里查看。 - Hemant Parmar
3个回答

6

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

它提供了一种将监听器连接到链的每个步骤的方法,以便您可以获取以下信息:

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
添加HttpLoggingInterceptor。它会记录请求的总时间。它还会记录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"

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接