Android retrofit 日志拦截器

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

背景

在使用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();
            requestBody.writeTo(buffer);
            Charset charset = Charset.forName("UTF-8");
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(charset);
            }
            if(isPlaintext(buffer)){
                sb.append(buffer.readString(charset));
                sb.append(" (Content-Type = ").append(contentType.toString()).append(",")
                        .append(requestBody.contentLength()).append("-byte body)");
            }else {
                sb.append(" (Content-Type = ").append(contentType.toString())
                        .append(",binary ").append(requestBody.contentLength()).append("-byte body omitted)");
            }
            sb.append("]");
            HLog.d(TAG, String.format(Locale.getDefault(), "%s %s", method, sb.toString()));
        }
        Response response = chain.proceed(request);
        long t2 = System.nanoTime();
        //the response time
        HLog.d(TAG,String.format(Locale.getDefault(),"Received response for [url = %s] in %.1fms",url, (t2-t1)/1e6d));

        //the response state
        HLog.d(TAG,String.format(Locale.CHINA,"Received response is %s ,message[%s],code[%d]",response.isSuccessful()?"success":"fail",response.message(),response.code()));

        //the response data
        ResponseBody body = response.body();

        BufferedSource source = body.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body.
        Buffer buffer = source.buffer();
        Charset charset = Charset.defaultCharset();
        MediaType contentType = body.contentType();
        if (contentType != null) {
            charset = contentType.charset(charset);
        }
        String bodyString = buffer.clone().readString(charset);
        HLog.d(TAG,String.format("Received response json string [%s]",bodyString));

        return response;
    }

    static boolean isPlaintext(Buffer buffer){
        try {
            Buffer prefix = new Buffer();
            long byteCount = buffer.size() < 64 ? buffer.size() : 64;
            buffer.copyTo(prefix, 0, byteCount);
            for (int i = 0; i < 16; i++) {
                if (prefix.exhausted()) {
                    break;
                }
                int codePoint = prefix.readUtf8CodePoint();
                if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
                    return false;
                }
            }
            return true;
        } catch (EOFException e) {
            return false; // Truncated UTF-8 sequence.
        }
    }

}

在上面的实现中,打印了请求的url、请求方法(get\post\put\delete…)、响应时间、响应状态、响应内容等。这里需要主要的是,在打印响应内容体的时候,或许你会遇到下面这个异常:

 java.lang.IllegalStateException: closed

这是因为你打印的时候直接调用了ResponseBody.string(),我们看下源码的实现

public final String string() throws IOException {
    return new String(bytes(), charset().name());
}

它调用了bytes(),我在接着看下

public final byte[] bytes() throws IOException {
    long contentLength = contentLength();
    if (contentLength > Integer.MAX_VALUE) {
      throw new IOException("Cannot buffer entire body for content length: " + contentLength);
    }

    BufferedSource source = source();
    byte[] bytes;
    try {
      bytes = source.readByteArray();
    } finally {
      Util.closeQuietly(source);
    }
    if (contentLength != -1 && contentLength != bytes.length) {
      throw new IOException("Content-Length and stream length disagree");
    }
    return bytes;
  }

看到finally部分,它已经将 BufferedSource 关闭掉了,这样到我们自己接口真正要处理的时候,它就会报错了,已经关闭的缓冲区就不能操作了。
那么上面LogInterceptor实际上是clone了一份BufferedSource 进行操作,这样不影响原来的BufferedSource。
也可以使用下面第二种方法,原理相同:

ResponseBody originalBody = response.body();
ResponseBody body = response.peekBody(originalBody.contentLength());
bodyString = body.string();
  • 给okhttp设置拦截器
OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
builder.addNetworkInterceptor(new NetworkInterceptor());
if(BuildConfig.DEBUG){
    //日志拦截器
    builder.addNetworkInterceptor(new LogInterceptor());
}
OkHttpClient client = builder.build();
retrofit = new Retrofit.Builder()
        .baseUrl(APIService.BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
        .client(client)
        .build();

相关Exception

 java.lang.IllegalStateException: closed
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值