Android Okhttp3 设置日志打印拦截器

Android Okhttp3 设置日志打印拦截器

方式1

/**
 * 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);
    }
}

调用:

.addInterceptor(new LoggerInterceptor(true)) // 添加日志打印拦截器

方式2(推荐)

添加依赖:

implementation 'com.squareup.okhttp3:logging-interceptor:3.6.0'

调用:

HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
// 包含header、body数据
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

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

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

您可以扫描屏幕右侧的二维码,来关注我的微信公众号,来学习更多的干货文章!

另外,我还建了一个免费的知识星球,感兴趣的微信扫码即可加入!

image

发布了138 篇原创文章 · 获赞 168 · 访问量 46万+

猜你喜欢

转载自blog.csdn.net/xinpengfei521/article/details/86612117
今日推荐