如何在Interceptor Android中获取401状态代码时更改活动

时间:2017-05-05 10:33:42

标签: android retrofit2 okhttp3

当我在API中获得 401状态代码时,我必须打开登录活动。我不想在每个API的onError方法中放置更改活动逻辑。我想要一个用于所有API的全局方法。 为此,我创建了一个拦截器

public class MyInterceptor extends BaseActivity implements Interceptor {

@Override
public Response intercept(Chain chain) throws IOException {
    Response response = chain.proceed(chain.request());

    if (response.code() == 401) {

        throw new RuntimeException(" Here you got 401 from API !");
    }

    return response;
}
}

这里我添加了这个拦截器

OkHttpClient.Builder builder=new OkHttpClient.Builder()
            .addNetworkInterceptor(new Interceptor() {
                @Override
                public okhttp3.Response intercept(Chain chain) throws IOException {
                    Request newRequest = chain.request().newBuilder()
                            .addHeader("Content-Type", "application/json")
                            .addHeader("User-Agent", "MyApp-Android-App")
                            .build();
                    return chain.proceed(newRequest);
                }
            })
            .addNetworkInterceptor(new StethoInterceptor())
            .addNetworkInterceptor(new MyInterceptor())
            .addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));

现在,我应该在哪里添加更改活动调用方法。我还使用RxRetrofit调用API。我想要一个全局方法来处理这个401响应。能否请我提供任何解决方案,我应该在哪里调用Activity change方法?

1 个答案:

答案 0 :(得分:0)

创建拦截器类

    def test_when_the_moon_is_in_the_seventh_house(self):
+        import hunter
+        hunter.trace(module_startswith='modlink')
        ...

现在添加拦截器

class HeaderInterceptor implements Interceptor
    {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request orignal = chain.request();
///--------------------------
            String token="your auth token"; //retriving depend upon you
//---------------------------

            Request request =orignal.newBuilder().header("Authorization", "Bearer "+ token)
                    .header("Accept", "application/json")
                    .header("Content-Type", "application/json").
                            method(orignal.method(), orignal.body())
                    .build();

            Response response =  chain.proceed(request);
            Log.d("MyApp", "Code : "+response.code());
            if (response.code() == 401){
                //handle it as per ur need
                return response;
            }
            return response;
        }
    }