2017-06-19 46 views
0

如果用戶是在我的應用程序被禁止,我的服務器返回以下響應:只要改造請求向服務器發出收聽全球所有回覆?

return response()->json([ 
    'banned' => 'You are banned.' 
], 403); 

所以,我需要能夠在全球範圍內檢查和閱讀的情況下,所有響應該用戶已被禁止。

這是我ApiClient.java,處理改造:

public class ApiClient { 

    public static final String API_URL = "http://www.website.com/api/"; 

    private static int defaultTimeout = 30; 

    private static OkHttpClient.Builder httpClient = 
      new OkHttpClient.Builder(); 

    private static Gson gson = new GsonBuilder() 
      .setLenient() 
      .create(); 

    private static Retrofit.Builder builder = 
      new Retrofit.Builder() 
        .addConverterFactory(ScalarsConverterFactory.create()) 
        .addConverterFactory(new NullOnEmptyConverterFactory()) 
        .addConverterFactory(GsonConverterFactory.create(gson)) 
        .baseUrl(API_URL); 

    private static Retrofit retrofit = builder.build(); 

    public static Retrofit getRetrofit() { 
     return retrofit; 
    } 

    public static <S> S createService(Class<S> serviceClass, Context context) { 
     return createService(serviceClass, context, null); 
    } 

    public static <S> S createService(Class<S> serviceClass, Context context, final String authToken) { 
     return createService(serviceClass, context, authToken, defaultTimeout); 
    } 

    public static <S> S createService(Class<S> serviceClass, Context context, final String authToken, int timeout) { 
     if (authToken != null) { 
      TokenInterceptor tokenInterceptor = new TokenInterceptor(authToken); 
      if (!httpClient.interceptors().contains(tokenInterceptor)) { 
       httpClient.addInterceptor(tokenInterceptor); 
      } 

      TokenAuthenticator tokenAuthenticator = new TokenAuthenticator(context, authToken); 
      httpClient.authenticator(tokenAuthenticator); 
     } 

     httpClient.connectTimeout(timeout, TimeUnit.SECONDS); 
     httpClient.writeTimeout(timeout, TimeUnit.SECONDS); 
     httpClient.readTimeout(timeout, TimeUnit.SECONDS); 

     builder.client(httpClient.build()); 
     retrofit = builder.build(); 

     return retrofit.create(serviceClass); 
    } 
} 

我怎麼能修改此以便它檢查從我的服務器每個響應,以檢查用戶是否已被禁止?在這種情況下,我會創建一個攔截器嗎?怎麼樣?

回答

1

是的,只是創建一個攔截器,尋找403響應。

public class BannedInterceptor implements Interceptor { 

    @Override 
    public Response intercept(@NonNull Chain chain) throws IOException { 
     Request request = chain.request(); 
     Response response = chain.proceed(request); 
     if (response.code() == 403) { 
      throw new IOException("user banned!"); 
     } 
     return response; 
    } 
} 

並將其添加到您的OkHttp客戶端。

httpClient.addInterceptor(new BannedInterceptor())

+0

是的,OP這是正確的路要走。 –

+0

'throw new IOException'就是我所缺少的。謝謝! – user456123