Retrofit OkHttpInterceptor中tag()返回null,如何获取@Tag参数值?
问题原因与解决方案
为什么request.tag()返回null?
Retrofit生成请求时,不会将@Tag注解的参数直接设为OkHttp Request的默认tag。它默认把包含接口方法信息、所有调用实参的Invocation对象设为请求的tag(对应request.tag(Invocation::class.java)的返回值),而request.tag()(无参)获取的是OkHttp Request的默认tag——这个值Retrofit并未设置,所以返回null。
如何获取@Tag参数值?
需要从Invocation对象中提取@Tag注解对应的实参值,具体实现如下:
完整Interceptor代码示例
import retrofit2.Invocation import retrofit2.http.Tag override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() val invocation = request.tag(Invocation::class.java) invocation?.run { val method = this.method() // 遍历方法参数,找到带@Tag注解的项 method.parameters.forEachIndexed { index, parameter -> if (parameter.isAnnotationPresent(Tag::class.java)) { val tagValue = this.arguments()[index] LogUtils.d("Hello tag: $tagValue") // 输出结果:Hello tag: mTag return@run // 找到目标tag后退出循环 } } } return chain.proceed(request) }
额外说明
- 若接口方法存在多个
@Tag参数,可通过@Tag("customName")指定名称,遍历阶段通过parameter.getAnnotation(Tag::class.java)?.value()判断,获取对应名称的tag值。 - 确保使用的Retrofit版本在2.6.0及以上,该版本开始包含
Invocation类。
内容的提问来源于stack exchange,提问作者Ishika Singh
相关产品推荐
相关产品推荐

