如何使用每个 API 的 OkHttp 拦截器在 Android Retrofit api 中获取 api 请求和 ap



我在调试的 BODY 中的 OkHttp3 拦截器的帮助下获得了 API 响应的响应时间,但我想要发布构建时每个 API 的服务器响应时间,我想上传它以进行跟踪器中的数据分析。我已经尝试过这两种方法 1. Response.sentRequestAtMillis(( 2. Response.receivedResponseAtMillis(( 但是我没有成功,所以请帮助我找到每个 api 的响应时间,要么可以通过计算 sentRequestAtMillis 和 receivedResponseAtMillis 或通过直接获取响应 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 tookMs,这将返回你想要的ms.. :)

最新更新