在WebView中设置Cookie [英] setting Cookies in WebView android

查看:629
本文介绍了在WebView中设置Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的 WebView 上设置一些cookie来打开一个与我在应用程序上使用的会话相同的浏览器。

I'm trying to set some cookies on my WebView to open a browser with the same session that I have on my app.

我读了很多答案,但他们不适合我。我发现的唯一解决方案是在 loadUrl ,硬编码的cookie数据在 extraHeaders ,但正如预期的那样

I read a lot of answers but they don't work for me. The only solution I've found is in the loadUrl, hardcode the cookie data in extraHeaders, but as expected this only works for this requests, and doesn't maintain the session.

我的代码是:

CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(mWebView.getContext());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.removeSessionCookie();
cookieManager.setCookie("http://xx.xxx.example.com","mid="+MySession.GetSession().sessionId+" ; Domain=.example.com");
cookieSyncManager.sync();

String cookie = cookieManager.getCookie("http://xx.xxx.example.com");

Log.d(LOGTAG, "cookie ------>"+cookie);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new TuWebViewClient());
mWebView.loadUrl("http://xx.xx.example.com");

getCookie()返回正确的数据,但是当我从服务器读取cookie时,这些是空的。哪里不对?请指教。
谢谢!!!

getCookie() returns the correct data, but when I read the cookies from the server, those are empty. What is wrong? Please advise. Thank you!!!

推荐答案

解决!问题是与webView,我不知道发生了什么,但如果我创建

Solved!!!! the problem is with the webView, I dont know what happend, but If I create the

WebView webView = new WebView(Activity.this);

如果我从活动读取webview从 findViewById()它不工作。

it works. If I read the webview from activity with findViewById() it doesn't work.

此外,如果您需要设置以前从网站收到的Cookie列表。
所有你需要做的是使用 for-loop 来遍历和设置它们。它帮助我解决了这种情况。

Also if you need to set a list of cookies that you received previously from a website. All you have to do is use a for-loop to go through and set all of them . It helped me to solve the situation

这篇关于在WebView中设置Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆