2016-06-07 91 views
2

我有一個場景,我添加一個攔截器,其中包含一個AuthorizationString在標題中從API獲取token。當我取回一個令牌時,我希望添加一個新的攔截器,它將接收到的令牌添加到所有後續請求的頭部。添加和刪除攔截器

如何刪除之前包含Authorization令牌的攔截器,因爲它不再需要?

private void removeAuthorizationInterceptor() 
{ 
    for (Interceptor interceptor : App.getOkHttpClient().newBuilder().networkInterceptors()) 
    { 
     // Find the interceptor which has the Authorization token and remove it 
    } 
} 

回答

3

你只需要創建一個新的OkHttpClient.Builder,然後改變列表。我認爲與您的代碼不同的是,您需要使用剛剛爲下一個請求構建的新客戶端。

OkHttpClient client = ...; 

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

這是Java 8代碼,但您可以更改用於Java 7的removeIf,例如,遍歷並將除攔截器以外的所有內容添加到新列表中。