Retrofit - Intercept responses globally

前端 未结 3 1112
旧巷少年郎
旧巷少年郎 2020-12-29 02:44

I\'d like to intercept all responses received by the retrofit engine, and scan for HTTP error code, for example error 403.

I\'m aware I can use the failure(RetrofitE

3条回答
  •  悲哀的现实
    2020-12-29 03:32

    OkHttpClient okHttpClient = new OkHttpClient.Builder()  
        .addInterceptor(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                okhttp3.Response response = chain.proceed(request);
    
                // todo deal with the issues the way you need to
                if (response.code() == 500) {
                    startActivity(
                            new Intent(
                                    ErrorHandlingActivity.this,
                                    ServerIsBrokenActivity.class
                            )
                    );
    
                    return response;
                }
    
                return response;
            }
        })
        .build();
    
    Retrofit.Builder builder = new Retrofit.Builder()  
            .baseUrl("http://your_url")
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create());
    
    Retrofit retrofit = builder.build(); 
    

    As you can see in the snippet above, the okhttp3.Response response = chain.proceed(request); line accesses the server response. Consequently, we can check the status code with if (response.code() == 500) and then open the ServerIsBrokenActivity.

提交回复
热议问题