Oma*_*abi 9 java android okhttp retrofit2 okhttp3
我知道可以通过a向所有请求添加拦截器OkHttpClient,但我想知道是否可以向所有请求添加标头,Okhttp除了一个请求或两个使用OkHttpClient.
例如,在我的API中,Authorization: Bearer token-here除了oauth/token(获取令牌)和api/users(注册用户)路由之外,所有请求都需要承载令牌(标头).是否可以为所有请求添加拦截器,除了使用OkHttpClient一步的排除的请求,或者我应该为每个请求单独添加标头?
Oma*_*abi 15
我找到了答案!
基本上我像往常一样需要一个拦截器,我需要检查那里的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;
}
}
Run Code Online (Sandbox Code Playgroud)
@Omar 答案很好:)但我找到了一种更干净的方法来使用自定义注释来实现。
添加注释
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
private annotation class DECRYPTRESPONSE
Run Code Online (Sandbox Code Playgroud)
在这样的拦截器中检查注释是 true 还是 false
val method = chain.request().tag(Invocation::class.java)!!.method()
if(method.isAnnotationPresent(DECRYPTRESPONSE::class.java)) {
//when annotion is present
} else..
Run Code Online (Sandbox Code Playgroud)
在retrofit接口中添加注解
@DECRYPTRESPONSE
@GET
Call<ItemsModel> getListing(@Url String url);
Run Code Online (Sandbox Code Playgroud)
下面是我的拦截器的完整代码,也不要忘记在 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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2578 次 |
| 最近记录: |