前言:
有时候我们会需要看我们给Server的request跟回传的response时,
如果需要一个一个去Log,就会有点麻烦,这时候我们可以用 intercept来帮助我们
将request的讯息一览无遗!
(图片取自:https://blog.csdn.net/qq402164452)
参考一下图片後,我们可以发现
首先先新增以下到 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)
再过来
1.实例化OkhttpClient
val client = OkHttpClient.Builder()
.build()
.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)的回传值
val request = chain.request()
val newRequest = chain.request().newBuilder()
.addHeader("Content-Type", "application/json")
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.build()
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)
}
好的,那来看一下实际拦截到的资料吧
若有任何错误烦请告知!
<<: 伸缩自如的Flask [day 21] Nginx with https
>>: Android 手机 行动电话 小人图示 talkback 无障碍按钮 导览列 捷径 协助工具按钮开关 设定 隐藏 开启
Visual Studio 是微软开发的整合开发环境(IDE),简称 VS。 VS 能开发的程序语言...
本篇大纲:d3.brush( )、brush 的 API 们、范例 今天我们要来看本系列的最後一个...
今天我们要实作一个华氏摄氏的温度转换器,首先先来设计他的介面 import javax.swing....
过渡 (transition) 是可以在不使用Flash动画或JavaScript的情况下,当元素从...
我想要的是可以一直问问题,而且回答年龄小於1就会break,在年龄在6跟12之间再问有没有父母 在线...