Android retrofit 日志拦截器

本文介绍了在Android开发中,使用Retrofit和OkHttp3时如何实现日志拦截器来方便调试网络请求。通过自定义Interceptor,可以打印请求地址、方法、响应时间和内容。在实现过程中要注意ResponseBody的处理,避免在拦截器中调用string()方法导致原始BufferedSource被关闭,影响后续处理。
摘要由CSDN通过智能技术生成

背景

在使用Android retrofit+rxjava时,想获知网络请求的一些参数,方便调试,比如:请求地址、请求响应时间、请求响应消息体等内容,虽然部分可以通过每个接口进行获知,但是这样极其不方便,那么有没有可以统一设置的方法呢?请接下去看。

日志拦截器

retrofit是使用okhttp3,做为网络请求,okhttp3有个Interceptor接口,可以对请求和响应进行拦截。通过这个机制,我们可以设计自己的一套日志拦截器,打印一些必要的信息。

  • 自定义拦截器

    首先要自己定义一个拦截器类,并实现Interceptor接口,在里面打印一些信息,如下LogInterceptor.java类。

public class LogInterceptor implements Interceptor{
   
    public static final String TAG = "LogInterceptor.java";
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        //the request url
        String url = request.url().toString();
        //the request method
        String method = request.method();
        long t1 = System.nanoTime();
        HLog.d(TAG,String.format(Locale.getDefault(),"Sending %s request [url = %s]",method,url));
        //the request body
        RequestBody requestBody = request.body();
        if(requestBody!= null) {
            StringBuilder sb = new StringBuilder("Request Body [");
            okio.Buffer buffer = new okio.Buffer();
            reques
  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值