我在BODY on Debug中借助OkHttp3阻断器获得了Api响应的响应时间,但我希望在发布时为每个api提供服务器响应时间,并希望将其上传到跟踪器中进行数据分析。我已经尝试过这两种方法1. Response.sentRequestAtMillis() 2. Response.receivedResponseAtMillis(),但是我没有成功,所以请帮助我找到每个api的响应时间--可以通过计算sentRequestAtMillis和receivedResponseAtMillis或直接获得响应Api示例(如(31 me ))中显示的响应时间。
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;
}
发布于 2019-10-21 05:38:36
sentRequestAtMillis
和receivedResponseAtMillis
param指的是设备时间而不是服务器时间,如果您更改设备的时间,它也会更改为此值。
根据https://square.github.io/okhttp/4.x/okhttp/okhttp3/-response/received-response-at-millis/
的说法,它是缓存的时间戳,所以这个方法不适合你。
用于您的解决方案:,您必须从发送时间戳,您可以从api的响应中获得这个参数,并且可以使用它。
如果您希望获得像31 ms 这样的毫秒响应,您可以重写类HttpLoggingInterceptor.kt,并在222行号中检查变量val tookMs
,这将返回您想要的ms。:)
https://stackoverflow.com/questions/58429689
复制相似问题