首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在所有API请求中添加拦截器,一个或两个除外?

如何在所有API请求中添加拦截器,一个或两个除外?
EN

Stack Overflow用户
提问于 2017-04-17 10:08:28
回答 2查看 4.2K关注 0票数 11

我知道可以通过OkHttpClient向所有请求添加一个拦截器,但我想知道是否可以向Okhttp中的所有请求添加头,但使用OkHttpClient的一两个请求除外。

例如,在我的API中,所有请求都需要一个承载令牌(Authorization: Bearer token-here报头),除了oauth/token (获取令牌)和api/users (注册用户)路由之外。是否可以在一步内为所有请求添加一个拦截器,但使用OkHttpClient的请求除外,还是应该为每个请求分别添加标头?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-04-17 11:08:45

我找到答案了!

基本上,我像往常一样需要一个拦截器,我需要检查那里的URL,以确定是否应该添加授权头。

代码语言:javascript
运行
复制
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;
    }
}
票数 22
EN

Stack Overflow用户

发布于 2021-08-23 23:57:14

@Omar的回答很好:)但是我找到了一种使用自定义注释实现的更干净的方法。

添加注释

代码语言:javascript
运行
复制
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
private annotation class DECRYPTRESPONSE

在这样的拦截器中检查注释是真还是假

代码语言:javascript
运行
复制
val method = chain.request().tag(Invocation::class.java)!!.method()
    if(method.isAnnotationPresent(DECRYPTRESPONSE::class.java)) {
       //when annotion is present
} else..

在改装接口中添加注释

代码语言:javascript
运行
复制
@DECRYPTRESPONSE
@GET
Call<ItemsModel> getListing(@Url String url);

下面是我的拦截器的完整代码,也不要忘记在Okhttpclient构建器中添加拦截器

代码语言:javascript
运行
复制
@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
        }
    }
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43449394

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档