我在我的Android应用程序中使用Retrofit 2.1.0进行API解析。我需要通过改造来解析API所花费的时间。
如何使用Retrofit 2获取请求/响应时间。
以下是我用于API解析的Retrofit Rest客户端调用。
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);
}
}
答案 0 :(得分:13)
您可以通过减去收到响应时的时间戳和发送请求时的时间戳来计算总往返时间。 Response对象中的这两个方法将为您提供这两个值
Response.sentRequestAtMillis()
Response.receivedResponseAtMillis()
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
long tx = response.sentRequestAtMillis();
long rx = response.receivedResponseAtMillis();
System.out.println("response time : "+(rx - tx)+" ms");
答案 1 :(得分:5)
您可以轻松地在响应的receivedResponseAtMillis()
部分中找到sendResponseAtMillis()
和raw()
,然后可以计算出差异
response.raw().receivedResponseAtMillis()
response.raw().sendResponseAtMillis()
答案 2 :(得分:1)
试试这个
if (BuildConfig.DEBUG) {
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(httpLoggingInterceptor);
}
还要添加
compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'
到你的app模块gradle文件
示例回复:
Date: Fri, 12 Aug 2016 07:33:23 GMT
OkHttp-Sent-Millis: 1470987074283
OkHttp-Received-Millis: 1470987074422