拦截器没有被称为retrofit2

Rya*_*ese 1 java android okhttp retrofit2

尝试添加拦截器以使用 okhttp3 和 Retrofit2 向请求添加标头。我注意到标头没有添加到请求中,并且我的 system.out.println 调试行从未被调用。不知道为什么,但这是我的代码:

创建服务:

OkHttpClient client = new OkHttpClient();

        client.newBuilder()
                .addInterceptor(new ServiceInterceptor(context))
                .authenticator(new MyAuthenticator(context))
                .build();

        service = (new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build())
                .create(Service.class);
Run Code Online (Sandbox Code Playgroud)

服务拦截器:

public class ServiceInterceptor implements Interceptor {

    private final Context context;

    public ServiceInterceptor(Context context){
        this.context = context;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        System.out.println("Interceptor");

        if(request.header("No-Authentication") == null){
            request = request.newBuilder()
                    .addHeader("User-Agent", "APP NAME")
                    .addHeader("Authorization", "bearer " + PreferenceManager.getDefaultSharedPreferences(context).getString("access_token", ""))
                    .build();
        }

        return chain.proceed(request);
    }
}
Run Code Online (Sandbox Code Playgroud)

不完全是问题的一部分,但我的验证器也从未被调用过......:

public class MyAuthenticator implements Authenticator {
    private Context context;

    public MyAuthenticator(Context context){
        this.context = context;
    }

    @Override
    public Request authenticate(Route route, Response response) throws IOException {
        //blah blah refresh token here...

        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

iag*_*een 5

您设置client为默认值OkHttpClient。您可以使用该客户端创建一个新客户端newBuilder(),但不要将其分配给任何内容。如果您不使用第一个客户端,则应该在第一次分配一个构建器 -

OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(new ServiceInterceptor(context))
            .authenticator(new MyAuthenticator(context))
            .build();
Run Code Online (Sandbox Code Playgroud)