MST
星途 面试题库

面试题:Kotlin中OkHttp拦截器链的基本原理及实现

请简述在Kotlin中OkHttp拦截器链的基本工作原理,并给出一个简单的自定义拦截器实现示例,说明该拦截器如何添加到OkHttp的拦截器链中。
34.7万 热度难度
编程语言Kotlin

知识考点

AI 面试

面试题答案

一键面试

OkHttp拦截器链基本工作原理

  1. 责任链模式:OkHttp的拦截器链基于责任链模式。每个拦截器都有机会处理请求和响应,并且可以决定是否将请求传递给下一个拦截器。
  2. 组成部分:拦截器链主要由多个拦截器(如应用层自定义拦截器、重试与重定向拦截器、桥接拦截器、缓存拦截器、连接拦截器等)组成。
  3. 工作流程:当一个请求进入OkHttp,首先会经过应用层添加的自定义拦截器,然后按照顺序依次经过其他内置拦截器。每个拦截器在处理请求时,会调用chain.proceed(request)将请求传递给下一个拦截器,下一个拦截器处理完返回响应后,当前拦截器再对响应进行后续处理。

自定义拦截器实现示例

import okhttp3.*
import java.io.IOException

class CustomInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request: Request = chain.request()
        println("CustomInterceptor: Request ${request.url}")
        val response: Response = chain.proceed(request)
        println("CustomInterceptor: Response ${response.code}")
        return response
    }
}

将自定义拦截器添加到OkHttp拦截器链中

import okhttp3.OkHttpClient
import java.io.IOException

fun main() {
    val client = OkHttpClient.Builder()
      .addInterceptor(CustomInterceptor())
      .build()

    val request = Request.Builder()
      .url("https://example.com")
      .build()

    client.newCall(request).enqueue(object : Callback {
        override fun onFailure(call: Call, e: IOException) {
            println("请求失败: ${e.message}")
        }

        override fun onResponse(call: Call, response: Response) {
            println("响应: ${response.body?.string()}")
        }
    })
}

在上述代码中,通过OkHttpClient.BuilderaddInterceptor方法将自定义的CustomInterceptor添加到拦截器链中。这样,当发起请求时,自定义拦截器就会按照拦截器链的规则执行。