How to add an interceptor to all API requests except one or two?

I know that you can add an interceptor to all requests through OkHttpClient , but I would like to know if headers can be added to all requests in Okhttp , with the exception of one request or two, using OkHttpClient .

For example, in my API, all requests require a carrier token ( Authorization: Bearer token-here header), except for oauth/token (for receiving a token) and api/users (for registering a user) routes. Is it possible to add an interceptor for all but excluded requests using OkHttpClient in one step or should I add headers separately for each request?

+5
source share
1 answer

I found the answer!

Basically I need an interceptor, as usual, and I had to check the URL there to see if I should add an authorization header or not.

 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; } } 
+8
source

Source: https://habr.com/ru/post/1266813/


All Articles