Search code examples
androidretrofit2

How to get API Request/ Response time using Retrofit 2


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);
    }

}

Solution

  • 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