Retrofit 拦截器实例记录

    由于项目中有个需求-单用户登录,要求拦截resultCode:209,并跳转到登录页面,在登录页面按返回键直接退出程序,所以有了以下的一个记录。

    项目中使用了retrofit2.0,retrofit中可以通过添加拦截器完成上面的要求。以下是具体的实现步骤:

    1)先定义一个拦截器

class SingleLoginInterceptor implements Interceptor {

        private Contextcontext;

        private final CharsetUTF8 = Charset.forName("UTF-8");

        SingleLoginInterceptor(Context context) {

        this.context = context;

    }

    @Override

    public Response intercept(Chain chain)throws IOException {

            Request request = chain.request();//获取request对象

            Response response = chain.proceed(request);//获取response对象,也就是返回结果的对象,以后所有的操作就在response上进行

            ResponseBody responseBody = response.body();

            BufferedSource source = responseBody.source();

            source.request(Long.MAX_VALUE);// Buffer the entire body.

            Buffer buffer = source.buffer();

            Charset charset =UTF8;

            MediaType contentType = responseBody.contentType();

            if (contentType !=null) {

                    try {

                    charset = contentType.charset(UTF8);

            }catch (UnsupportedCharsetException e) {

                    e.printStackTrace();

            }

        }

            String rBody = buffer.clone().readString(charset);//以上,通过转型到“UTF-8”,以及通过深度拷贝获取新的可操作的数据。

            try {

                    JSONObject jsonObject =new JSONObject(rBody);

                    int resultCode = jsonObject.getInt("resultcode");

                    if (resultCode ==209) {//通过返回的特性code做具体操作,这里如果是209,就认为是别的地方已经使用同样的账号进行登录成功

                            EventModel event =new EventModel();

                            event.isLogout =true;

                            RxBus.getInstance().post(event);

                            SPUtils.getInstance(Constant.SHARED_NAME).put(Constant.LOGIN_KEY,false);

                            Intent intent =new Intent(context, LoginActivity.class);

                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK |                             Intent.FLAG_ACTIVITY_TASK_ON_HOME);//这里是为了满足,跳转到登录页面之后,如果按返回键就退出程序

                            context.startActivity(intent);

                            ToastUtils.showLong("您已在别的地方登录");

                    }

                }catch (JSONException e) {

                    e.printStackTrace();

            }

            return response;

}

2.添加到retrofit

private static volatile OkHttpClient mOkHttpClient =new OkHttpClient.Builder()

 mOkHttpClient  .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)

                          .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)

                          .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)

                         .retryOnConnectionFailure(true)

                        .addInterceptor(new SingleLoginInterceptor(DCApplication.getAppContext()))

                        .build();     

3.附录第1,2步中用到的类

public class RxBus {

        private static volatile RxBussRxBus;

        // 主题

        private final FlowableProcessormBus;

     // PublishSubject只会把在订阅发生的时间点之后来自原始Observable的数据发射给观察者

        public RxBus() {

                mBus = PublishProcessor.create().toSerialized();

        }

        // 单例RxBus

        public static RxBus getInstance() {

                    if (sRxBus ==null) {

                            synchronized (RxBus.class) {

                                    if (sRxBus ==null) {

                                            sRxBus =new RxBus();

                                    }

                            }

                    }

        return sRxBus;

}

        // 提供了一个新的事件

        public void post(Object o) {

                mBus.onNext(o);

        }

        // 根据传递的 eventType 类型返回特定类型(eventType)的 被观察者

           public Flowable toFlowable(Class eventType) {

                    return mBus.ofType(eventType);

            }

}

4.另外,记录几种可以关闭多个activity的方法

参考链接:

Android开发之关闭多个Activity https://blog.csdn.net/weiwozhiyi/article/details/50791416

你可能感兴趣的:(Retrofit 拦截器实例记录)