Android中OKHttp保存Cookie并传入WebView
Cookie是服务器为客户端分配的一个键值对的表,和session不同的是cookie存储在客户端。服务器通过Response.addCookie()为客户端添加Cookie数据,再从Request.getCookie()中获取数据。
在Android开发中,有时我们需要调用http的接口登录帐号,然后使用cookie作为登录标记来进行网页浏览。此时就需要从http请求中取到cookie数据并保存起来,在使用webView进行页面访问时再将cookie数据设置到webview上。本文以OKHttp为讨论对象,下面是从OKHttp中取到Cookie数据的过程:
一.定义cookie接收监听器
/** * This Interceptor add all received Cookies to the app DefaultPreferences. * Your implementation on how to save the Cookies on the Preferences MAY VARY. * <p> * Created by tsuharesu on 4/1/15. */ 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请求
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设置
/** * 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中去
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。
相关推荐
hzyuhz 2020-07-04
明瞳 2020-06-12
LowisLucifer 2020-04-23
houmenghu 2020-11-17
kentrl 2020-11-10
逍遥友 2020-10-26
jincheng 2020-09-01
Blueberry 2020-08-15
xclxcl 2020-08-03
zmzmmf 2020-08-03
阳光之吻 2020-08-03
PkJY 2020-07-08
89407707 2020-06-27
服务器端攻城师 2020-06-26
阳光岛主 2020-06-25
笨重的蜗牛 2020-06-20
xuanwenchao 2020-06-14
Lophole 2020-06-13