听取全球的所有回复?

时间:2017-06-19 16:28:22

标签: android retrofit retrofit2

如果我的应用程序禁止用户,我的服务器将返回以下响应:

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

因此,每当向服务器发出Retrofit请求时,我都需要能够全局检查并读取所有响应,以防用户被禁止。

以下是处理Retrofit的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 个答案:

答案 0 :(得分: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())