Android Okhttp3 设置日志打印拦截器

2020-02-27 17:28:49 浏览数 (1)

Android Okhttp3 设置日志打印拦截器

方式1

代码语言:javascript复制
/**
 * Created by x-sir on 2018/8/3 :)
 * Function:LoggerInterceptor
 */
public class LoggerInterceptor implements Interceptor {

    private static String TAG = "LoggerInterceptor";
    private boolean isDebug;

    public LoggerInterceptor(boolean isDebug) {
        this(TAG, isDebug);
    }

    public LoggerInterceptor(String tag, boolean isDebug) {
        this.isDebug = isDebug;
        TAG = tag;
    }

    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Request request = chain.request();
        if (BuildConfig.DEBUG || isDebug) {
            LogUtil.i(TAG, String.format("发送请求:%s on %s%n%s%n%s",
                    request.url(), chain.connection(), request.headers(), request.body()));
        }
        return chain.proceed(request);
    }
}

调用:

代码语言:javascript复制
.addInterceptor(new LoggerInterceptor(true)) // 添加日志打印拦截器

方式2(推荐)

添加依赖:

代码语言:javascript复制
implementation 'com.squareup.okhttp3:logging-interceptor:3.6.0'

调用:

代码语言:javascript复制
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
// 包含header、body数据
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

//http数据log,日志中打印出HTTP请求&响应数据
.addInterceptor(loggingInterceptor)

本文首发于我的微信公众号,更多干货文章,请扫描二维码订阅哦:

0 人点赞