美文网首页
Retrofit 常用功能介绍

Retrofit 常用功能介绍

作者: younger_lei | 来源:发表于2018-01-19 20:00 被阅读0次

    用Retrofit已经一年多了吧,越来越觉的好用、简单、漂亮。一次不可能把所有的功能都用上,所以我准备时常更新这篇文章,方便日后查看、复习。

    统一设置头信息Cookie

    如果在每个请求中设置的话太反锁了,所以应该在过滤器中统一设置,当cookie不为空时,说明是第一次请求,获取保存cookie

    .addInterceptor(new Interceptor() {
                        @Override
                        public Response intercept(Chain chain) throws IOException {
                            Response response = chain.proceed(chain.request());
                            if (!response.headers("Set-Cookie").isEmpty()){
                                StringBuffer stringBuffer = new StringBuffer();
                                String session = response.headers("Set-Cookie").get(0);
                                stringBuffer.append(session.substring(0, session.indexOf(";")));
                                stringBuffer.append(";");
                                save(stringBuffer.toString());//保存cookie代码
                            }
                            return response;
                        }
                    })
    

    然后再添加一个过滤器,每当请求数据时将保存的cookie加入

    .addInterceptor(new Interceptor() {
                        @Override
                        public Response intercept(Chain chain) throws IOException {
                            Request.Builder builder = chain.request().newBuilder();
                            if (GlobalApplication.getLoginSession() != null)
                                builder.addHeader("Cookie",getCookie());//获取之前保存的cookie
                            return chain.proceed(builder.build());
                        }
                    })
    

    相关文章

      网友评论

          本文标题:Retrofit 常用功能介绍

          本文链接:https://www.haomeiwen.com/subject/kkeaoxtx.html