将cookie注入WebView不起作用

时间:2010-09-15 16:02:50

标签: java android

我将我的cookie注入login.php页面时遇到了一些问题。这是代码:

LinearLayout lLayout = (LinearLayout)findViewById(R.id.linearlayoutIdLogin);
lLayout.setVisibility(View.GONE); //make my standard layout inivisible
LinearLayout lWeb = (LinearLayout)findViewById(R.id.webviewId); 
lWeb.setVisibility(View.VISIBLE); //make my webview visible
WebView browse = (WebView)findViewById(R.id.webViewBrowse);

上面的代码是正确的。我加载了WebView,但页面说我需要登录。

这是cookie注入,对我不起作用。

Cookie setcookie = cookie.get(1);
Cookie othercookie = cookie.get(0);
/* I assign my two cookies from a List<Cookie>. cookie.get() 
brings the element I need. The cookies overall contains two fields. Therefore 
the get 1 and get 0. All this works, I have tested to make a Toast to
print out the cookies */

//Here it must be anything I'm doing wrong?
CookieManager cookieManager = CookieManager.getInstance(); 
cookieManager.setAcceptCookie(true);
cookieManager.setCookie("http://www.thedomain.com", setcookie.getValue());

browse.setWebViewClient(new WebViewClient(){ });
browse.loadUrl("mypagewhenloggedin.php");

有什么想法吗?已经坚持了几个小时。提前谢谢!

编辑代码: 忘了说我也添加了这个cookie。

cookieManager.setCookie("http://www.thedomain.com", othercookie.getValue());

2 个答案:

答案 0 :(得分:3)

getDomain()上使用Cookie,而不是假设域名为"http://www.thedomain.com"。另外,考虑使用Wireshark或其他东西来检查HTTP请求,以查看与正在运行的浏览器请求相比可能出现的格式错误。

答案 1 :(得分:1)

尝试此更改

http://developer.android.com/reference/android/webkit/CookieSyncManager.html

CookieManager cookieManager = CookieManager.getInstance(); 

// new line
CookieSyncManager.createInstance(this);

cookieManager.setAcceptCookie(true);
cookieManager.setCookie("http://www.thedomain.com", setcookie.getValue());

// new line
CookieSyncManager.getInstance().sync();

browse.setWebViewClient(new WebViewClient(){ });
browse.loadUrl("mypagewhenloggedin.php");