Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Profiling http request with OkHttp

Tags:

android

okhttp

How to track detailed request time with OkHttp.

I want to get:

  • connection time;
  • sending time;
  • receiving time;

I tried to use Interceptors mechanism, but it provides only total request time.

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();
}
like image 917
mgukov Avatar asked Nov 10 '15 07:11

mgukov


2 Answers

Use response.receivedResponseAtMillis() And response.sentRequestAtMillis() instead

like image 145
JunYao Yuan Avatar answered Sep 30 '22 16:09

JunYao Yuan


There is an implementation of a logging interceptor provided by Square here. It does log the total request time. It also will log the Ok-Http-Sent and Ok-Http-Received headers. I do not know enough of the implementation details to know what those mean, and the documentation is sparse.

I also recommend Facebook's 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 of the interceptor may also help you derive your own logging mechanism.

There is a pending stetho issue that discusses adding more detailed information, similar to executing a query in the browser (profiling dns lookup, ssl handshaking, etc), however it looks like it requires (significant?) modifications to OkHttp before being viable.

like image 35
CoatedMoose Avatar answered Sep 30 '22 16:09

CoatedMoose