How to get API Request/ Response time using Retrofit 2
You can calculate the total round trip time by substracting the timestamp when response is received and timestamp when the request is sent. These two methods from the Response object will give you these two values
Response.sentRequestAtMillis()
Response.receivedResponseAtMillis()
RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder() .url(url) .post(body) .build(); Response response = client.newCall(request).execute(); long tx = response.sentRequestAtMillis(); long rx = response.receivedResponseAtMillis(); System.out.println("response time : "+(rx - tx)+" ms");
It's easy you can find the receivedResponseAtMillis()
and the sendResponseAtMillis()
in the raw()
part of the response and then you can calculate the difference
response.raw().receivedResponseAtMillis()
response.raw().sendResponseAtMillis()
Try this
if (BuildConfig.DEBUG) {
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(httpLoggingInterceptor);
}
also add
compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'
to your app module gradle file
Sample response:
Date: Fri, 12 Aug 2016 07:33:23 GMT
OkHttp-Sent-Millis: 1470987074283
OkHttp-Received-Millis: 1470987074422