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

前言:

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

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

将request的讯息一览无遗!

https://ithelp.ithome.com.tw/upload/images/20210603/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"

//okhttp
implementation '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 请求和响应+Header
  • HttpLoggingInterceptor.Level.BODY 请求和响应+Header+Body

再过来

1.实例化OkhttpClient

val client = OkHttpClient.Builder()
.build()
  1. 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)


}

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

https://ithelp.ithome.com.tw/upload/images/20210603/20138017L9oA5sDRqq.jpg

若有任何错误烦请告知!


<<:  伸缩自如的Flask [day 21] Nginx with https

>>:  Android 手机 行动电话 小人图示 talkback 无障碍按钮 导览列 捷径 协助工具按钮开关 设定 隐藏 开启

[C# WinForm] 建立第一个应用程序 Hello World

Visual Studio 是微软开发的整合开发环境(IDE),简称 VS。 VS 能开发的程序语言...

Day16-D3 的 Brush 刷子

本篇大纲:d3.brush( )、brush 的 API 们、范例 今天我们要来看本系列的最後一个...

[Day28] CH13:画出你的藏宝图——事件处理(上)

今天我们要实作一个华氏摄氏的温度转换器,首先先来设计他的介面 import javax.swing....

Day 24 CSS3 < 过渡 transition>

过渡 (transition) 是可以在不使用Flash动画或JavaScript的情况下,当元素从...

如何完成这while回圈

我想要的是可以一直问问题,而且回答年龄小於1就会break,在年龄在6跟12之间再问有没有父母 在线...