我有一个场景,我添加了一个拦截器,该拦截器在报头中包含一个Authorization String,以便从token中返回一个API。当我得到一个令牌时,我希望添加一个新的拦截器,它会将收到的令牌添加到所有后续请求的头部。
由于不再需要Authorization令牌,如何删除包含该令牌的前一个拦截器?
private void removeAuthorizationInterceptor()
{
for (Interceptor interceptor : App.getOkHttpClient().newBuilder().networkInterceptors())
{
// Find the interceptor which has the Authorization token and remove it
}
}发布于 2016-06-09 05:16:40
您只需创建一个新的OkHttpClient.Builder,然后更改列表。我认为与您的代码的不同之处在于,您需要使用刚刚为下一个请求构建的新客户端。
OkHttpClient client = ...;
OkHttpClient.Builder b = client.newBuilder();
b.networkInterceptors().removeIf(MyInterceptor.class::isInstance);
client2 = b.build();这是Java8代码,但您可以更改Java7的removeIf,例如,迭代并将除拦截器之外的所有内容添加到新列表中。
https://stackoverflow.com/questions/37690824
复制相似问题