简体   繁体   中英

How to get api request and api response time in Android Retrofit api using OkHttp Interceptor for each api?

I got the response time on the Api Response with the help of OkHttp3 Interceptor within the BODY on Debug but i want the server response time for each api on Release build and i want to upload it for data analysis in tracker. I have already tried this both method 1. Response.sentRequestAtMillis() 2. Response.receivedResponseAtMillis() But i didn't get the success so please help me to find the response time for each api either it is possible by calculating the sentRequestAtMillis and receivedResponseAtMillis OR by getting the directly which is shown on the Response Api example like (31ms) .

Api Request :-

D/OkHttp: --> POST http://api.globoapps.in/abc/updateUserDetail
D/OkHttp: Content-Type: application/json; charset=UTF-8
D/OkHttp: Content-Length: 208
D/OkHttp: {"androidId":"996e831d34ba64b0","id":4,"deviceToken":"abcd"}
D/OkHttp: --> END POST (208-byte body)

Api Response :-

D/OkHttp: <-- 200 http://api.globoapps.in/abc/updateUserDetail (31ms)
D/OkHttp: Server: nginx/1.12.2
D/OkHttp: Date: Thu, 17 Oct 2019 09:30:24 GMT
D/OkHttp: Content-Type: application/json;charset=UTF-8
D/OkHttp: Transfer-Encoding: chunked
D/OkHttp: Connection: keep-alive
D/OkHttp: {"id":4,"status":"Success"}
D/OkHttp: <-- END HTTP (533-byte body)

Code (MainBaseApplication.java) :-

   public static Retrofit getRetrofitInstance() {
        if (retrofit == null) {

            OkHttpClient.Builder httpClient = new OkHttpClient.Builder();


            httpClient.readTimeout(30, TimeUnit.SECONDS);
            httpClient.connectTimeout(30, TimeUnit.SECONDS);
            httpClient.writeTimeout(30, TimeUnit.SECONDS);

            httpClient.addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request original = chain.request();

                    Request.Builder builder = original.newBuilder();
                    builder.method(original.method(), original.body());
//                    builder.header("Accept", "application/json");
                    if (TOKEN.length() > 0)
                        builder.header("Authorization", TOKEN);
                    return chain.proceed(builder.build());
                }
            });

            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            if (BuildConfig.DEBUG) {
                interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            } else {
                interceptor.setLevel(HttpLoggingInterceptor.Level.NONE);
            }
            httpClient.addInterceptor(interceptor);

            OkHttpClient client = httpClient.build();
//            Response response = client.newCall(request).execute();
//             tx = response.sentRequestAtMillis();
//            rx = response.receivedResponseAtMillis();
//            System.out.println("response time : "+(rx - tx)+" ms");
            Gson gson = new GsonBuilder()
                    .setLenient()
                    .create();

            retrofit = new Retrofit.Builder()
                    .baseUrl(WebAPI.BASE_URL)
                    .client(httpClient.build())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
        }
        return retrofit;
    }

sentRequestAtMillis and receivedResponseAtMillis param are refer to device time not server time, if you change time of device it will change to this values also.

according to https://square.github.io/okhttp/4.x/okhttp/okhttp3/-response/received-response-at-millis/ it is timestamp from cached sometime so this method not work for you.

For your solution: you have to send timestamp from api and you can get that param from api's response and you can use it.

If you want millisecond of response like 31ms you can override class HttpLoggingInterceptor.kt and check variable val tookMs in 222 line number that will return you ms which you want.. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM