Android中OKHttp保存Cookie并传入WebView

Cookie是服务器为客户端分配的一个键值对的表,和Session不同的是Cookie存储在客户端。服务器通过Response.addCookie()为客户端添加Cookie数据,再从Request.getCookie()中获取数据。

在Android开发中,有时我们需要调用HTTP的接口登录帐号,然后使用Cookie作为登录标记来进行网页浏览。此时就需要从HTTP请求中取到Cookie数据并保存起来,在使用WebView进行页面访问时再将Cookie数据设置到WebView上。本文以OKHttp为讨论对象,下面是从OKHttp中取到Cookie数据的过程:

定义Cookie接收拦截器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* This Interceptor add all received Cookies to the app DefaultPreferences.
* Your implementation on how to save the Cookies on the Preferences MAY VARY.
*/
public class ReceivedCookiesInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
List<String> cookieList = originalResponse.headers("Set-Cookie");
if (cookieList != null) {
for (String s : cookieList) { //Cookie的格式为: cookieName=cookieValue;path=xxx
//保存你需要的cookie数据
}
}
return originalResponse;
}
}

使用OKHttp发送简单Get请求

1
2
3
4
Request request = new Request.Builder().url("Your URL").build();
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new ReceivedCookiesInterceptor()); //你定义的cookie接收监听器
Response response = client.newCall(request).execute();

初始化WebView设置

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* init WebView Settings
**/
private void initWebViewSettings() {
//设置可以访问文件
getSettings().setAllowFileAccess(true);
//如果访问的页面中有Javascript,则WebView必须设置支持Javascript
getSettings().setJavaScriptEnabled(true);
getSettings().setAllowFileAccess(true);
getSettings().setAppCacheEnabled(true);
getSettings().setDomStorageEnabled(true);
getSettings().setDatabaseEnabled(true);
}

将Cookie设置到WebView中去

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public void syncCookie(Context context, String url) {
try {
CookieSyncManager.createInstance(context);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.removeSessionCookie(); //移除
cookieManager.removeAllCookie();
String oldCookie = cookieManager.getCookie(url);

URL aURL = new URL(url);

StringBuilder sbCookie = new StringBuilder();
sbCookie.append(String.format(CookieName + "=%s", "Your saved Cookie Value."));
//webview在使用cookie前会前判断保存cookie的domain和当前要请求的domain是否相同,相同才会发送cookie
sbCookie.append(String.format(";domain=%s", aURL.getHost())); //注意:是getHost(),不是getAuthority()
sbCookie.append(String.format(";path=%s", "/"));

String cookieValue = sbCookie.toString();
cookieManager.setCookie(url, cookieValue);
CookieSyncManager.getInstance().sync();

String newCookie = cookieManager.getCookie(url);
} catch(Exception e) {
}
}

注意:在loadUrl()之前,设置Cookie

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :