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
.
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. 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?
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.
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;
}
}