【问题标题】:How to get API Request/ Response time using Retrofit 2如何使用 Retrofit 2 获取 API 请求/响应时间
【发布时间】:2016-08-10 12:21:54
【问题描述】:

我在我的 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);
    }

}

【问题讨论】:

标签: android retrofit2


【解决方案1】:

您可以通过减去收到响应时的时间戳和发送请求时的时间戳来计算总往返时间。 Response 对象中的这两个方法将为您提供这两个值

  1. Response.sentRequestAtMillis()
  2. 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");
    

【讨论】:

  • 这不能做一个全局统计
【解决方案2】:

很容易你可以在响应的raw()部分找到receivedResponseAtMillis()sendResponseAtMillis(),然后你可以计算出差异

response.raw().receivedResponseAtMillis()
response.raw().sendResponseAtMillis()

【讨论】:

    【解决方案3】:

    试试这个

       if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            httpClient.addInterceptor(httpLoggingInterceptor);
        }
    

    还要加

    compile 'com.squareup.okhttp3:logging-interceptor:3.2.0' 
    

    到您的应用模块 gradle 文件

    示例响应:

    Date: Fri, 12 Aug 2016 07:33:23 GMT
    OkHttp-Sent-Millis: 1470987074283
    OkHttp-Received-Millis: 1470987074422
    

    【讨论】:

    • 感谢您提供的解决方案。但它仍然没有提供任何超时日志。如何使用 OkHttp 打印日志。
    • 你会得到时间登录到你的控制台,如上
    • 你是否使用 HttpLoggingInterceptor.Level.BODY 作为日志级别?
    • 如何从调用对象或请求对象获取代码中的响应时间?
    猜你喜欢
    • 2020-02-14
    • 1970-01-01
    • 2016-09-02
    • 1970-01-01
    • 2018-01-15
    • 2016-11-03
    • 2013-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多