2017-04-17 216 views
5

我知道這是可能通過OkHttpClient一個攔截器添加到所有的要求,但我想知道是否有可能以頭添加到除用OkHttpClient一個請求或兩個Okhttp所有請求。如何添加攔截器,除了一個或兩個的所有API請求?

例如,在我的API所有請求都需要承載令牌(Authorization: Bearer token-here頭)除oauth/token(以獲得令牌)和api/users(註冊的用戶)的路線。是否有可能增加一個攔截器除了使用在一個步驟或者我應該單獨添加標題爲每個請求OkHttpClient排除那些所有的請求?

回答

8

我找到了答案!

基本上我需要一個像往常一樣的攔截器,我需要檢查的URL那裏知道我是否應該添加授權頭。

import java.io.IOException; 

import okhttp3.Interceptor; 
import okhttp3.Request; 
import okhttp3.Response; 

/** 
* Created by Omar on 4/17/2017. 
*/ 

public class NetInterceptor implements Interceptor { 
    @Override 
    public Response intercept(Chain chain) throws IOException { 
     Request request = chain.request(); 
     if (request.url().encodedPath().equalsIgnoreCase("/oauth/token") 
       || (request.url().encodedPath().equalsIgnoreCase("/api/v1/users") && request.method().equalsIgnoreCase("post"))) { 
      return chain.proceed(request); 
     } 
     Request newRequest = request.newBuilder() 
       .addHeader("Authorization", "Bearer token-here") 
       .build(); 
     Response response = chain.proceed(newRequest); 
     return response; 
    } 
}