【问题标题】:Interceptor no getting called retrofit2拦截器没有被称为改造2
【发布时间】:2016-11-27 11:16:29
【问题描述】:

尝试使用 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);

服务拦截器:

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);
    }
}

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

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

【问题讨论】:

    标签: java android retrofit2 okhttp3


    【解决方案1】:

    您将client 设置为默认OkHttpClient。您使用newBuilder() 从该客户端创建一个新客户端,但不要将其分配给任何东西。如果你不使用第一个客户端,你应该第一次分配一个构建器——

    OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new ServiceInterceptor(context))
                .authenticator(new MyAuthenticator(context))
                .build();
    

    【讨论】:

    • 我遇到了同样的问题。我没有将它分配给新变量,因此所有配置设置都丢失了。但是现在我已经将它分配给它可以工作的变量。
    猜你喜欢
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    • 2016-05-02
    相关资源
    最近更新 更多