1,本处用的是Volley网络请求框架,在网络请求成功回调之后有返回cookie值过来这个时候在Volley的回调方法
@Override protected Response<String> parseNetworkResponse(NetworkResponse response) { try { Map<String, String> responseHeaders = response.headers; String rawCookies = responseHeaders.get("Set-Cookie"); System.out.println("rawCookies==="+rawCookies); String dataString = new String(response.data, "UTF-8");
//储存cookie值 MyApp.setCookieValue(rawCookies);
return Response.success(dataString, HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } }
2,在webView要加载网页之前将cookie值同步
String url ="http://xxxx/xxl/login";
AppUtils.synCookies(this,url, MyApp.getCookieValue()); webView.loadUrl(url);贴上工具类里的2个方法:/** *同步cookie * @param context * @param url */ public static void synCookies(Context context, String url,String cookieValue) { CookieSyncManager.createInstance(context); CookieManager cookieManager = CookieManager.getInstance(); cookieManager.setCookie(url,cookieValue); CookieSyncManager.getInstance().sync(); } /** * 移除cookie * @param context */ private void removeCookie(Context context) { CookieSyncManager.createInstance(context); CookieManager cookieManager = CookieManager.getInstance(); cookieManager.removeAllCookie(); CookieSyncManager.getInstance().sync(); }