如何在Kotlin中定义@JWT注解为Retrofit添加Bearer头
实现Retrofit自定义@JWT注解自动添加Bearer前缀
方案概述
通过OkHttp拦截器结合Retrofit的Invocation对象,识别接口方法中带有@JWT注解的参数,自动为其添加Bearer 前缀并注入Authorization请求头。该方案仅处理标记了注解的参数,不会影响其他接口的Authorization头逻辑。
步骤1:定义自定义@JWT注解
创建用于标记JWT令牌参数的注解,指定作用于参数且保留至运行时:
@Target(AnnotationTarget.VALUE_PARAMETER) @Retention(AnnotationRetention.RUNTIME) annotation class JWT
步骤2:实现OkHttp拦截器
编写拦截器,通过Invocation获取接口方法的参数信息,识别@JWT注解并处理令牌格式:
class JwtInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() // 获取请求对应的接口方法与参数信息 val invocation = request.tag(Invocation::class.java) ?: return chain.proceed(request) val method = invocation.method() val args = invocation.arguments() // 遍历参数,处理带@JWT注解的令牌 method.parameterAnnotations.forEachIndexed { index, annotations -> if (annotations.any { it is JWT }) { val token = args[index] as? String ?: run { // 非String类型参数直接跳过,可根据需求添加日志或异常 return@forEachIndexed } // 构建新请求,注入格式化后的Authorization头 val authorizedRequest = request.newBuilder() .header("Authorization", "Bearer $token") .build() return chain.proceed(authorizedRequest) } } return chain.proceed(request) } }
步骤3:配置Retrofit与OkHttp
将自定义拦截器添加到OkHttpClient,并构建Retrofit实例:
val okHttpClient = OkHttpClient.Builder() .addInterceptor(JwtInterceptor()) .build() val retrofit = Retrofit.Builder() .baseUrl("https://your-api-base-url.com/") .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) // 替换为你使用的Converter .build()
步骤4:在接口中使用@JWT注解
在需要添加JWT头的接口方法参数上标记@JWT,直接传入原始令牌即可:
interface ApiService { @GET("user/profile") fun getUserProfile(@JWT token: String): Call<UserProfileResponse> }
注意事项
- Retrofit版本需≥2.6.0(支持
Invocation对象) @JWT注解仅支持String类型参数,非String类型会被拦截器跳过- 若方法存在多个
@JWT参数,拦截器仅处理第一个(可根据需求修改逻辑)
内容的提问来源于stack exchange,提问作者Arman TabibZadeh
相关产品推荐
相关产品推荐

