【OkHttp拦截器 Intercept + Android Kotlin】拦截送出去的request

前言:

有时候我们会需要看我们给Server的request跟回传的response时,

如果需要一个一个去Log,就会有点麻烦,这时候我们可以用 intercept来帮助我们

将request的讯息一览无遗!

http://img2.58codes.com/2024/20138017jy5RXsnIOz.png
(图片取自:https://blog.csdn.net/qq402164452)

参考一下图片后,我们可以发现

因为intercept是在发送给network之前先拦截的,所以可以做到Query加密,以及统一新增Header等功能有两种拦截器,一个是Application intercept,另一个是Network intercept,我们这次主要练习的是 Application intercept

首先先新增以下到 gradle

//intercept拦截器implementation "com.squareup.okhttp3:logging-interceptor:4.9.1"//okhttpimplementation 'com.squareup.okhttp3:okhttp:4.9.1'

再过来实例化 HttpLoggingInterceptor

val logging: HttpLoggingInterceptor =        HttpLoggingInterceptor().setLevel(if(BuildConfig.DEBUG){HttpLoggingInterceptor.Level.BODY}else        {HttpLoggingInterceptor.Level.NONE})

好的,我们可以看到后面有一个 setLevel,这边有以下四个选项

(挑选自己想要看到的Log选择Level,并且设定只有在DEBUG模式才可以看到Body)

HttpLoggingInterceptor.Level.NONE 不打印HttpLoggingInterceptor.Level.BASIC 请求和响应HttpLoggingInterceptor.Level.HEADERS 请求和响应+HeaderHttpLoggingInterceptor.Level.BODY 请求和响应+Header+Body

再过来

1.实例化OkhttpClient

val client = OkHttpClient.Builder().build()
client里面新增 addInterceptor
.addInterceptor(object : Interceptor{override fun intercept(chain: Interceptor.Chain): okhttp3.Response{val newRequest = chain.request().newBuilder().addHeader("Content-Type", "application/json").addHeader("Content-Type", "application/x-www-form-urlencoded").build()return chain.proceed(newRequest)    }})

我们这边用匿名内部类实例化继承 Interceptor的 class ,并override intercept的 funtion,

并且拥有 chain.procedd(newRequest)的回传值

override fun intercept 里面只有一个引数-chain,透过chain的request方法可以获取当前的 request (没任何修改过的request)
val request = chain.request()
也可以透过 newBuilder() 来新建一个request,并且包含原本的request
val newRequest = chain.request().newBuilder().addHeader("Content-Type", "application/json").addHeader("Content-Type", "application/x-www-form-urlencoded").build()
最后再透过继续 chain.proceed() 来继续拦截的执行
return chain.proceed(newRequest)

最后在另外新增一个 addInterceptor,并把刚刚实例化的HttpLoggingInterceptor放进去

.addInterceptor(logging)

参考文章:https://codertw.com/android-开发/348129/

完整的code 如下

object BookApi {    private val BASE_URL = "your_base_url"    private val moshi = Moshi.Builder()        .add(KotlinJsonAdapterFactory())        .build()    val logging: HttpLoggingInterceptor =        HttpLoggingInterceptor().setLevel(if(BuildConfig.DEBUG){HttpLoggingInterceptor.Level.BODY}else        {HttpLoggingInterceptor.Level.NONE})    val client = OkHttpClient.Builder()              .addInterceptor(object : Interceptor {            override fun intercept(chain: Interceptor.Chain): okhttp3.Response {                 val newRequest = chain.request().newBuilder()                    .addHeader("Content-Type", "application/json")                    .addHeader("Content-Type", "application/x-www-form-urlencoded")                    .build()                val request = chain.request()                Timber.d("RequestNew $newRequest")                Timber.d("Request $request")                return chain.proceed(newRequest)            }        })        .addInterceptor(logging)        .build()    private val retrofit = Retrofit.Builder()        .addCallAdapterFactory(CoroutineCallAdapterFactory())        .addConverterFactory(MoshiConverterFactory.create(moshi))        .baseUrl(BASE_URL)        .client(client)        .build()    val retrofitService = retrofit.create(BookApiService::class.java)}

好的,那来看一下实际拦截到的资料吧

http://img2.58codes.com/2024/20138017L9oA5sDRqq.jpg

若有任何错误烦请告知!


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章