Retrofit使用OkHttp保存和添加cookie

Retrofit的cookie的保存和添加都可以用Interceptor来实现 
下面是接收请求中返回并保存cookie的代码示例:

public class ReceivedCookiesInterceptor implements Interceptor { private Context context; public ReceivedCookiesInterceptor(Context context) { super(); this.context = context; } @Override public Response intercept(Chain chain) throws IOException { Response originalResponse = chain.proceed(chain.request()); //这里获取请求返回的cookie if (!originalResponse.headers("Set-Cookie").isEmpty()) { final StringBuffer cookieBuffer = new StringBuffer(); //最近在学习RxJava,这里用了RxJava的相关API大家可以忽略,用自己逻辑实现即可.大家可以用别的方法保存cookie数据 Observable.from(originalResponse.headers("Set-Cookie")) .map(new Func1<String, String>() { @Override public String call(String s) { String[] cookieArray = s.split(";"); return cookieArray[0]; } }) .subscribe(new Action1<String>() { @Override public void call(String cookie) { cookieBuffer.append(cookie).append(";"); } }); SharedPreferences sharedPreferences = context.getSharedPreferences("cookie", Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("cookie", cookieBuffer.toString()); editor.commit(); } return originalResponse; }

 

向请求中添加cookie,代码如下:

public class AddCookiesInterceptor implements Interceptor { private Context context; public AddCookiesInterceptor(Context context) { super(); this.context = context; } @Override public Response intercept(Chain chain) throws IOException { final Request.Builder builder = chain.request().newBuilder(); SharedPreferences sharedPreferences = context.getSharedPreferences("cookie", Context.MODE_PRIVATE); //最近在学习RxJava,这里用了RxJava的相关API大家可以忽略,用自己逻辑实现即可 Observable.just(sharedPreferences.getString("cookie", "")) .subscribe(new Action1<String>() { @Override public void call(String cookie) { //添加cookie builder.addHeader("Cookie", cookie); } }); return chain.proceed(builder.build()); } }

 

在Retrofit做如下设置即可在每次请求中保存和添加cookie: 
本人使用的Retrofit2.0可能Retrofit1.9中代码略有不同,但这个思路应该也可以用在1.9版本中,希望对大家有所帮助

   public static OkHttpClient getClient(Context context) {
        OkHttpClient client = getUnsafeOkHttpClient();
        client.interceptors().add(new ReceivedCookiesInterceptor(context)); client.interceptors().add(new AddCookiesInterceptor(context)); return client; }


转载至:https://blog.csdn.net/u012045061/article/details/50452767
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LuckyTHP

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值