我知道可以通过OkHttpClient
向所有请求添加一个拦截器,但我想知道是否可以向Okhttp
中的所有请求添加头,但使用OkHttpClient
的一两个请求除外。
例如,在我的API中,所有请求都需要一个承载令牌(Authorization: Bearer token-here
报头),除了oauth/token
(获取令牌)和api/users
(注册用户)路由之外。是否可以在一步内为所有请求添加一个拦截器,但使用OkHttpClient
的请求除外,还是应该为每个请求分别添加标头?
发布于 2017-04-17 11:08:45
我找到答案了!
基本上,我像往常一样需要一个拦截器,我需要检查那里的URL,以确定是否应该添加授权头。
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by Omar on 4/17/2017.
*/
public class NetInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (request.url().encodedPath().equalsIgnoreCase("/oauth/token")
|| (request.url().encodedPath().equalsIgnoreCase("/api/v1/users") && request.method().equalsIgnoreCase("post"))) {
return chain.proceed(request);
}
Request newRequest = request.newBuilder()
.addHeader("Authorization", "Bearer token-here")
.build();
Response response = chain.proceed(newRequest);
return response;
}
}
发布于 2021-08-23 23:57:14
@Omar的回答很好:)但是我找到了一种使用自定义注释实现的更干净的方法。
添加注释
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
private annotation class DECRYPTRESPONSE
在这样的拦截器中检查注释是真还是假
val method = chain.request().tag(Invocation::class.java)!!.method()
if(method.isAnnotationPresent(DECRYPTRESPONSE::class.java)) {
//when annotion is present
} else..
在改装接口中添加注释
@DECRYPTRESPONSE
@GET
Call<ItemsModel> getListing(@Url String url);
下面是我的拦截器的完整代码,也不要忘记在Okhttpclient构建器中添加拦截器
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
private annotation class DECRYPTRESPONSE
class DecryptInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response = chain
.run {
proceed(request())
}
.let { response ->
return@let if (response.isSuccessful) {
val body = response.body!!
val contentType = body.contentType()
val charset = contentType?.charset() ?: Charset.defaultCharset()
val buffer = body.source().apply { request(Long.MAX_VALUE) }.buffer()
val bodyContent = buffer.clone().readString(charset)
val method = chain.request().tag(Invocation::class.java)!!.method()
if(method.isAnnotationPresent(DECRYPTRESPONSE::class.java)) {
response.newBuilder()
.body(ResponseBody.create(contentType, bodyContent.let(::decryptBody)))
.build()
}
else{
response.newBuilder()
.body(ResponseBody.create(contentType, bodyContent))
.build()
}
} else response
}
private fun decryptBody(content: String): String {
return content //your decryption code
}
}
https://stackoverflow.com/questions/43449394
复制相似问题