Okhttp-LoggingInterceptor的简单使用

概述

Okhttp除了提供强大的get,post网络请求外,还包含请求日志的拦截器,可以监视,重写,重试调用请求。

简单使用

我们在构造OkHttpClient时,通过addInterceptor()方法添加我们需要的过滤器。

   object OkhttpUtils{
    ……
    private var client:OkHttpClient

    //init方法在kotlin静态类中,是最先被调用的方法
    init {
        val httpLoggingInterceptor = HttpLoggingInterceptor()
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
        //构造Http对象
        client = OkHttpClient().newBuilder()
            .connectTimeout(10L, TimeUnit.SECONDS)
            .readTimeout(10L, TimeUnit.SECONDS)
            .writeTimeout(10L, TimeUnit.SECONDS)
            .addInterceptor(httpLoggingInterceptor)
            .build()
    }
    
    ……
   }
httpLoggingInterceptor

使用默认的httpLoggingInterceptor打印日志如下,可以发现,除了关键信息外,还有一些冗余或者很长的非关键日志,我们可以通过自定义日志过滤器找到我们需要的信息。

 自定义LoggingInterceptor

1:写一个类,实现Interceptor接口,复写intercept(chain:Interceptor.Chain):Response{}方法

package com.example.okhttp.http

import android.util.Log
import okhttp3.Interceptor
import okhttp3.MediaType
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okhttp3.ResponseBody
import okhttp3.ResponseBody.Companion.toResponseBody
import okio.Buffer

class TypeInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val time = System.currentTimeMillis()
        //获取request
        val request = chain.request()
        //request.body转字符串
        val str = request.body?.toString() ?: "request.body is null"
        Log.d(
            Hiokhttp.TAG, String.format(
                "sending request url is %s with body is %s",
                request.url, str
            )
        )
        //获取response,因为okhttp的原理,response.body在获取一次以后,
        //就不能再生成响应流了,因此需要构造一个新的返回
        val response = chain.proceed(request = request)
        //将response的数据保存到新的response
        val data: String = response.body?.string() ?: "response.body is null"

        //构建新的response
        val medieType = request.body?.contentType()
        val newBody = data.toResponseBody(medieType)
        val end = System.currentTimeMillis()
        Log.d(
            Hiokhttp.TAG, String.format(
                "received url is %s with host time %.1f ms ",
                request.url, (end - time) / 1e3
            )
        )
        return response.newBuilder().body(newBody).build()

    }
}

下面看一下效果,我们将请求url和请求体,以及花费时间 成功打印了出来,避免冗余繁琐的日志。

猜你喜欢

转载自blog.csdn.net/qq_34123324/article/details/131870094