解决Android webview设置cookie和cookie丢失的问题
作者:Te_small 时间:2021-09-12 21:55:52
Android页面嵌套了一个h5,H5页面内部有用户登陆页面,发现h5页面的登陆功能无法使用,一直登陆失败。和web那边商量一会,发现js写入的cookie丢失了。所有需要Android这边在重写写入一次。
mWebView = view.findViewById(R.id.mall_view);
settings = mWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setLoadsImagesAutomatically(true);
settings.setDomStorageEnabled(true);
//不缓存
settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
mWebView.setWebViewClient(new MyWebViewClient());
class MyWebViewClient extends WebViewClient{
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url != "") {
//重点写入cookie
HashMap<String, String> map = new HashMap<>();
map.put("Referer", view.getUrl());
view.loadUrl(url, map);
}
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
//获取登陆后的cookie,看是否写入
CookieManager cookieManager = CookieManager.getInstance();
String CookieStr = cookieManager.getCookie(url);
super.onPageFinished(view, url);
}
}
以上就解决了登陆失败的问题!
还有就是登陆状态的同步,需要保存和设置cookie
/**
* 获取接口中的cookie
* @param loginUrl
*/
private void syncCookie(final String loginUrl) {
new Thread(new Runnable() {
@Override
public void run() {
try {
StringBuilder builder = new StringBuilder();
URL url= null;
byte[] data = builder.toString().getBytes("UTF-8");
url = new URL(loginUrl);
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length",
Integer.toString(data.length));
connection.setRequestMethod("GET");
connection.setInstanceFollowRedirects(false);
OutputStream os = connection.getOutputStream();
os.write(data);
os.close();
int aRstCode = connection.getResponseCode();
if (aRstCode == HttpURLConnection.HTTP_OK) {
cookie = connection.getHeaderField("Set-Cookie");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
//设置cookie
if(cookie != null && cookie.length() > 0){
android.webkit.CookieManager cookieManager =
android.webkit.CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.setCookie(SysParam.shoppingMall, cookie);
CookieSyncManager.getInstance().sync();
}
补充知识:android webview带cookie访问url
问题描述
在原生和h5混合开发的时候会遇到这么一个问题,用webview加载某个url时,你只是app登录了账号,但是网页却没有,所有会禁止访问此url,webview就会显示白屏。
所以要访问此url,需要带上cookie进行访问。这个cookie就是用app登录时所存储的cookie
实现方法和一些环境
网络请求方式
HttpsUrlConnection
这里既然用到了HttpsUrlConnection 说明我所加载的url是https协议
所以webview加载的时候会白屏
报错信息:
1
这是由于证书和域名不匹配,我的调试环境在内网服务器上,而证书是绑定在公网的域名上的。
所以需要webView跳过证书验证,
跳过证书验证
webView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
Log.e("app_name",error.toString());
handler.proceed();
}
});
然后设置cookie
cookie是在app使用HttpsUrlConnect发起登录请求时保存在本地的cookie
app登录成功后保存cookie到本地
SharedPreferences sharedPreferences = getSharedPreferences("login",MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
String cookieval = conn.getHeaderField("Set-Cookie");
editor.putString("all_cookie",cookieval);
是一个结构如下的值:
SESSION=f19b09e9-69b2-4ab4-9daf-ea224523a092; Path=/; Secure; HttpOnly
写入cookie
/**
*@param cookie 上面获取到的存储在本地的cookie字符串
*@param url 要加载的页面url
*/
private void setCookie(String cookie,String url) {
String StringCookie = cookie;
CookieManager cookieManager = CookieManager.getInstance();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
cookieManager.removeSessionCookies(null);
cookieManager.flush();
} else {
cookieManager.removeSessionCookie();
CookieSyncManager.getInstance().sync();
}
cookieManager.setAcceptCookie(true);
cookieManager.setCookie(url, StringCookie);
}
所有关键代码
SharedPreferences sharedPreferences = getSharedPreferences("login",MODE_PRIVATE);
String cookie = sharedPreferences.getString("session","");
String all_cookie = sharedPreferences.getString("all_cookie","");
Log.e("weibiao",all_cookie);
webView = findViewById(R.id.other_account_service_webview);
webView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
Log.e("weibiao",error.toString());
handler.proceed();
}
});
initWebViewSettings();//webview的一些设置
setCookie(all_cookie,url);//在loadurl之前调用此方法
webView.loadUrl(url);
来源:https://blog.csdn.net/Te_small/article/details/83987893
标签:Android,webview,cookie
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Java多线程事务管理的实现
2023-07-26 22:58:20
Java利用反射自动封装成实体对象的方法
2022-01-06 05:54:29
Android中 视频屏幕左半部分上下滑动改变亮度右半部分上下滑动改变声音
2021-08-13 02:57:12
C#获取Windows进程监听的TCP/UDP端口实例
2021-11-20 13:06:21
java synchronized 锁机制原理详解
2021-10-15 05:29:47
![](https://img.aspxhome.com/file/2023/9/64219_0s.png)
struts2 validation.xml 验证规则代码解析
2021-09-14 22:01:27
Java线程池大小的设置方法实例
2022-10-04 04:20:19
秒懂Kotlin之Java工程师快速掌握Kotlin的技巧
2023-07-09 21:25:19
![](https://img.aspxhome.com/file/2023/7/75697_0s.png)
Android数据库中事务操作方法之银行转账示例
2023-07-22 07:56:13
C#实现打印与打印预览功能的思路及代码
2021-09-17 02:51:06
Json读写本地文件实现代码
2023-10-10 06:03:21
基于CXF搭建webService的实例讲解
2023-07-02 10:41:34
Android自定义ViewPager指示器
2023-11-29 03:30:31
![](https://img.aspxhome.com/file/2023/7/138207_0s.jpg)
教你java面试时如何聊单例模式
2022-04-14 05:32:57
![](https://img.aspxhome.com/file/2023/6/119186_0s.png)
Android NTP 时间同步机制详解
2023-03-29 23:02:09
![](https://img.aspxhome.com/file/2023/1/123321_0s.jpg)
springboot实现在工具类(util)中调用注入service层方法
2021-06-17 20:02:51
![](https://img.aspxhome.com/file/2023/6/60616_0s.png)
mybatis中的mapper.xml使用循环语句
2022-02-06 22:23:13
详解C#之事件
2022-01-07 22:18:14
![](https://img.aspxhome.com/file/2023/2/85652_0s.png)
Android使用分类型RecyclerView仿各大商城首页
2021-06-29 12:08:23
![](https://img.aspxhome.com/file/2023/6/137676_0s.jpg)
java实现动态 代理方法浅析
2023-11-28 23:33:59