用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());
}
})