我在我的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);
}
}
Run Code Online (Sandbox Code Playgroud)
Rak*_*esh 14
您可以通过减去收到响应时的时间戳和发送请求时的时间戳来计算总往返时间.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");
Run Code Online (Sandbox Code Playgroud)小智 6
这很容易就可以找到receivedResponseAtMillis()和sendResponseAtMillis()在raw()回应的一部分,然后你可以计算差值
response.raw().receivedResponseAtMillis()
response.raw().sendResponseAtMillis()
Run Code Online (Sandbox Code Playgroud)
尝试这个
if (BuildConfig.DEBUG) {
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(httpLoggingInterceptor);
}
Run Code Online (Sandbox Code Playgroud)
还添加
compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'
Run Code Online (Sandbox Code Playgroud)
到您的应用程序模块 gradle 文件
响应示例:
Date: Fri, 12 Aug 2016 07:33:23 GMT
OkHttp-Sent-Millis: 1470987074283
OkHttp-Received-Millis: 1470987074422
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7100 次 |
| 最近记录: |