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 HashMapmap = 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);
以上这篇解决Android webview设置cookie和cookie丢失的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。