java - 如何在 Android Retrofit api 中为每个 api 使用 OkHttp 拦截器获取 api 请求和 api 响应时间?

标签 java android api retrofit2 okhttp

我在 Debug 的 BODY 中借助 OkHttp3 Interceptor 获得了 Api Response 的响应时间,但我想要 Release build 上每个 api 的服务器响应时间,我想上传它以在跟踪器中进行数据分析。我已经尝试过这两种方法 1. Response.sentRequestAtMillis() 2. Response.receivedResponseAtMillis() 但是我没有成功,所以请帮助我找到每个 api 的响应时间,或者可以通过计算 sentRequestAtMillis 和 receivedResponseAtMillis 或直接获取 Response Api 示例中显示的响应时间,如 (31ms) .

API 请求 :-

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 响应:-

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)

代码 (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;
    }

最佳答案

sentRequestAtMillisreceivedResponseAtMillis 参数是指设备时间而不是服务器时间,如果您更改设备时间,它也会更改为该值。

根据 https://square.github.io/okhttp/4.x/okhttp/okhttp3/-response/received-response-at-millis/ 它是某个时间缓存的时间戳所以这种方法对你不起作用。

对于您的解决方案:您必须从 api 发送时间戳,您可以从 api 的响应中获取该参数并可以使用它。

如果你想要像 31ms 这样的毫秒响应,你可以覆盖类 HttpLoggingInterceptor.kt并检查 222 行号中的变量 val takeMs ,它会返回你想要的 ms .. :)

关于java - 如何在 Android Retrofit api 中为每个 api 使用 OkHttp 拦截器获取 api 请求和 api 响应时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58429689/

相关文章:

android - 如何获取日期、小时、分钟以达到特定日期

java - 是否实现扩展类

java - 什么是NullPointerException,我该如何解决?

android - Adobe 是否为其 PDF 阅读器提供 Android SDK 或 API?

api - Azure 移动服务的自定义 API 中的多个路由的权限

Python gevent+瓶子。查询 API。如何使用gevent防止超时锁?

php - 使用 Dwolla 的 API 汇款并使用 PHP 进行汇款?

java - 为什么 Files.newByteChannel 不返回 FileChannel?

java - spring boot oauth2 feign 允许匿名请求

android - 在 Android 中查找用户的当前位置