登录Retrofit 2.0 [英] Logging in Retrofit 2.0

查看:100
本文介绍了登录Retrofit 2.0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Retrofit的先前版本使用 RestAdapter ,并提供了启用日志的功能.为什么在 Retrofit 2.0 中删除了该功能?

Previous version of Retrofit uses RestAdapter and has provision of enabling the Logs. Why that feature is removed in Retrofit 2.0?

要启用日志,我必须这样做.

To enable log, I have to do..

 Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    /** Handles Log */
    retrofit.client().interceptors().add(new LoggingInterceptor());


class LoggingInterceptor implements Interceptor {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
    Request request = chain.request();

    long t1 = System.nanoTime();
    Logger.d(String.format("Sending request %s on %s%n%s",
            request.url(), chain.connection(), request.headers()));

    Response response = chain.proceed(request);

    long t2 = System.nanoTime();
    Logger.d(String.format("Received response for %s in %.1fms%n%s",
            response.request().url(), (t2 - t1) / 1e6d, response.headers()));

   // Logger.d(""+new String(response.body().bytes()));
    return response;
}

这是唯一的解决方案?以前的规定非常方便...

This is the Only solution for this? Previous provision was very handy...

推荐答案

对于改造2的登录,okhttp具有以下记录器:

For logging in retrofit 2 okhttp has the following logger:

 private OkHttpClient getOkHttpClient() {
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    if (BuildConfig.LOG_HTTP_CALLS) {
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
    }

    return new OkHttpClient.Builder()
            .addInterceptor(logging).build();
}

并且build.gradle中的依赖项是

compile 'com.squareup.okhttp3:logginginterceptor:2.1.0'

这篇关于登录Retrofit 2.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆