场景:在网络请求中,有些接口需要添加token认证,有些接口不需要
- 自定义注解类
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Token { boolean value() default true; }
|
- 在
Interceptor
拦截器中实现
Java:
@Override public Response intercept(Chain chain) throws IOException { Request original = chain.request(); Request.Builder builder = original.newBuilder(); final Token annotation = Objects.requireNonNull(original.tag(Invocation.class)).method().getAnnotation(Token.class); String accessToken = CacheUtil.getAccessToken(); if (annotation == null || annotation.value()) { if (!TextUtils.isEmpty(accessToken)) { builder.addHeader(ACCESS_TOKEN_NAME, "bearer " + accessToken); } } builder.addHeader(AUTHORIZATION,AUTHORIZATION_VALUE); return response; }
|
Kotlin:
override fun intercept(chain: Interceptor.Chain): Response { val original = chain.request() val builder = original.newBuilder() val response = chain.proceed(builder.build()) builder.addHeader(AUTHORIZATION, AUTHORIZATION_VALUE) val annotation = original.tag(Invocation::class.java)?.method()?.getAnnotation(Token::class.java) annotation?.value.run { accessToken?.let { builder.addHeader(ACCESS_TOKEN_NAME,"bearer $it") } } return response }
|
3.使用:在 Service接口的方法上,添加注解
@Token(value = false) suspend fun login( @Field("username") username: String, @Field("password") password: String ): LoginClient
|