class TokenHeadInterceptor : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response? {
var response: Response? = null
var updateRequest: Request? = null
try {
val request = chain.request()//拿到请求对象 用于创建新的请求对象
updateRequest = request.newBuilder().//没有发现服务器的 request
method(request.method(), request.body()).build()
response = chain.proceed(updateRequest)//设置新的服务器request 获得返回的response
val responseBody = response!!.body()//服务器返回的response
val content = responseBody!!.string()
return response.newBuilder().body(ResponseBody.create(response.body()!!.contentType(), content)).build()//设置新的服务器返回response
} catch (e: Exception) {
e.printStackTrace()
}
return response
}
}
调用的时候
object RetrofitFactory {
internal var httpClient = OkHttpClient.Builder()
.addInterceptor(TokenHeadInterceptor())
.readTimeout(8, TimeUnit.SECONDS)
.writeTimeout(8, TimeUnit.SECONDS)
.connectTimeout(5, TimeUnit.SECONDS)
.build()
internal var retrofit = Retrofit
.Builder()
.baseUrl(Constant.URL)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create(GsonUtil.buildGosn()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
}
1.chain.proceed处Bug:
java.io.IOException: unexpected end of stream on Connection{192.168.24.100:9041, proxy=DIRECT@ hostAddress=/192.168.24.100:9041 cipherSuite=none protocol=http/1.1}
2.解决:
将addNetworkInterceptor 改成 addInterceptor
3.Okhttp 的addInterceptor 和 addNetworkInterceptor 的区别?
addInterceptor(应用拦截器):
1,不需要担心中间过程的响应,如重定向和重试.
2,总是只调用一次,即使HTTP响应是从缓存中获取.
3,观察应用程序的初衷. 不关心OkHttp注入的头信息如: If-None-Match.
4,允许短路而不调用 Chain.proceed(),即中止调用.
5,允许重试,使 Chain.proceed()调用多次.
addNetworkInterceptor(网络拦截器):
1,能够操作中间过程的响应,如重定向和重试.
2,当网络短路而返回缓存响应时不被调用.
3,只观察在网络上传输的数据.
4,携带请求来访问连接.