0

改造:我想使用 Tag 注解在请求中传递一些数据,然后我想从拦截器中截取这些数据。

这样的东西

我怎么能像这样使用它,但不使用 Call

@Target(AnnotationTarget.VALUE_PARAMETER,
        AnnotationTarget.FUNCTION
    )
    @Retention(AnnotationRetention.RUNTIME)
    annotation class Tagz

@GET
suspend fun getUsers(@Tagz value: CachePolicy.Type, @Url placeholder: String): Response<UserEntity?>

使用上面的东西给我带来了这个:

java.lang.IllegalArgumentException: No Retrofit annotation found. (parameter #1)

如何将参数中的值作为请求中的标记传递?

顺便说一句:我能够使用这样的标签

@Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER)
    @Retention(AnnotationRetention.RUNTIME)
    annotation class CachePolicyTag(val value: CachePolicy.Type)

@GET
@CachePolicyTag(CachePolicy.Type.DefaultCache)
suspend fun getUsers(@Url placeholder: String): Response<UserEntity?>

但不是注释函数,我希望它在这个挂起函数中作为参数传递。

4

1 回答 1

1

我使用改造 @TAG 来传递标签值并在 okhttp 拦截器中拦截。

@GET
suspend fun getUsers(@Tag cacheType: CachePolicy.Type, @Url placeholder: String): Response<UserEntity?>

在我的 Okhttp 拦截器中

override fun intercept(chain: Interceptor.Chain): Response {
        val request =  chain.request() 
        val response = chain.proceed(request)
        request.tag(Invocation::class.java)?.let {
                kotlin.runCatching {
                   val cachePolicyType = it.arguments()[0] as CachePolicy.Type
                } 
        }
        return response
}

如果出现任何错误或类转换异常,它也不会在 runCatching 块之外抛出任何异常。

于 2021-09-02T09:33:01.337 回答