2

I have a scenario where I add an interceptor containing an Authorization String in the header to get back a token from the API. When I get back a token, I wish to add a new interceptor which will add the received token to the header of all subsequent requests.

How do I remove the previous Interceptor which contains the Authorization token since it's no longer needed?

private void removeAuthorizationInterceptor()
{
    for (Interceptor interceptor : App.getOkHttpClient().newBuilder().networkInterceptors())
    {
        // Find the interceptor which has the Authorization token and remove it
    }
}
Subby
  • 5,370
  • 15
  • 70
  • 125
  • I'm facing the same issue in my context I have three different APIs and only one need to use interceptor (AddHeaderAndCookie) which add api signature and cookie required for this API, other APIS don't need this, how can i achieve this – Sam Jul 04 '18 at 02:32

1 Answers1

4

You just need to create a new OkHttpClient.Builder and then mutate the list. I think the difference from your code is that you need to use the new client you just built for the next request.

OkHttpClient client = ...;

OkHttpClient.Builder b = client.newBuilder();
b.networkInterceptors().removeIf(MyInterceptor.class::isInstance);
client2 = b.build();

This is Java 8 code, but you can change the removeIf for Java 7, e.g. iterate through and add everything except your interceptor to a new list.

Yuri Schimke
  • 12,435
  • 3
  • 35
  • 69