Java – how do I add interceptors to all API requests except one or two?

I know that an interceptor can be added to all requests through okhttpclient, but I want to know whether headers can be added to all requests in okhttp, except for one request or two using okhttpclient

For example, in my API, except for OAuth / token and API / users routing, all requests require bearer token here header Can okhttpclient be used in one step to add interceptors for all requests except excluded requests, or should headers be added separately for each request?

Solution

I found the answer!

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

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;
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>