Retrofit使用OkHttp保存和添加cookie
oepp8190
8年前
<p>Retrofit的cookie的保存和添加都可以用<strong>Interceptor</strong>来实现<br> 下面是接收请求中返回并保存cookie的代码示例:</p> <pre> <code class="language-java">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; }</code></pre> <p>向请求中添加cookie,代码如下:</p> <pre> <code class="language-java">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()); } }</code></pre> <p>在Retrofit做如下设置即可在每次请求中保存和添加cookie:<br> 本人使用的Retrofit2.0可能Retrofit1.9中代码略有不同,但这个思路应该也可以用在1.9版本中,希望对大家有所帮助</p> <pre> <code class="language-java"> public static OkHttpClient getClient(Context context) { OkHttpClient client = getUnsafeOkHttpClient(); client.interceptors().add(new ReceivedCookiesInterceptor(context)); client.interceptors().add(new AddCookiesInterceptor(context)); return client; }</code></pre> <p><br> <a href="/misc/goto?guid=4959675374965240657">阅读原文</a></p>