I am using Retrofit 2.1.0 for API parsing in my android application. I need the time taken by retrofit to parse the API.
How to obtain the Request/ response time using Retrofit 2.
Below is the Retrofit Rest Client Call I am using for API parsing.
public static class ServiceGenerated {
static OkHttpClient httpClient = new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request.Builder ongoing = chain.request().newBuilder();
return chain.proceed(ongoing.build());
}
})
.build();
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(RetrofitUtils.API_BASE_URL)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create());
public static <S> S createService(Class<S> serviceClass) {
Retrofit retrofit = builder.client(httpClient).build();
return retrofit.create(serviceClass);
}
}
create(Api. class); Call<ResponseBody> call = api. checkLevel(1); call. enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { JsonObject post = new JsonObject().
If we want to consume the API asynchronously, we call the service as follows: String username = "sarahjean"; Call<User> call = apiService. getUser(username); call. enqueue(new Callback<User>() { @Override public void onResponse(Call<User> call, Response<User> response) { int statusCode = response.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With