简体   繁体   English

API请求除了一两个之外,如何添加拦截器?

[英]How to add interceptor to all API requests except one or two?

I know it's possible to add an interceptor to all requests through an OkHttpClient , but I would like to know if it's possible to add headers to all requests in Okhttp except for one request or two using the OkHttpClient .我知道可以通过OkHttpClient向所有请求添加拦截器,但我想知道是否可以向Okhttp中的所有请求添加标头,除了一个或两个使用OkHttpClient的请求。

For example, in my API all requests require a bearer token ( Authorization: Bearer token-here header) except for the oauth/token (to get a token) and api/users (to register a user) routes.例如,在我的API中,除了oauth/token (获取令牌)和api/users (注册用户)路由之外,所有请求都需要持有者令牌( Authorization: Bearer token-here header)。 Is it possible to add an interceptor for all requests except the excluded ones using the OkHttpClient in one step or should I add the headers individually for each request?是否可以一步为使用OkHttpClient的排除请求之外的所有请求添加拦截器,或者我应该为每个请求单独添加标头?

I found the answer! 我找到了答案!

Basically I needed an interceptor as usual and I needed to check the URL there to know whether I should add the authorization header or not. 基本上我像往常一样需要一个拦截器,我需要检查那里的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;
    }
}

@Omar answer is Good:) but I found a more clean way to implement using custom annotation. @Omar 回答很好 :) 但我找到了一种更简洁的方法来使用自定义注释来实现。

Add annotation添加注释

@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
private annotation class DECRYPTRESPONSE

check if the annotation is true or false in an intercepter like this在这样的拦截器中检查注释是真还是假

val method = chain.request().tag(Invocation::class.java)!!.method()
    if(method.isAnnotationPresent(DECRYPTRESPONSE::class.java)) {
       //when annotion is present
} else..

add an annotation in retrofit interface在retrofit接口添加注解

@DECRYPTRESPONSE
@GET
Call<ItemsModel> getListing(@Url String url);

below is the complete code of my interceptor also don't forget to add intercepter in the Okhttpclient builder下面是我的拦截器的完整代码也不要忘记在 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
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM