最近项目中JS和本地交互需要在网页加载时向WebView同步token来判断当前是否登录APP
代码如下:
public static void setCookie(Context context, String url) {
try {
CookieSyncManager.createInstance(context);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.removeSessionCookie();//移除
cookieManager.removeAllCookie();
//本地存储的token
String token = MyApp.getInstance().getSpUtil().getUserToken();
StringBuilder sbCookie = new StringBuilder();
sbCookie.append("token=" + token);
//.***.com为api地址或者项目域名
sbCookie.append(";domain=.***.com;path=/");
String cookieValue = sbCookie.toString();
cookieManager.setCookie(url, cookieValue);
CookieSyncManager.getInstance().sync();
} catch (Exception e) {
e.printStackTrace();
}
}