Android 上的 WebView 和 Cookie [英] WebView and Cookies on Android
问题描述
我在 appspot 上有一个应用程序,它可以通过常规浏览器正常工作,但是当通过 Android WebView 使用时,它无法设置和读取 cookie.顺便说一句,我不是试图在此 Web 应用程序外部"获取 cookie,一旦 WebView 访问了 URL,所有处理、ID 等都可以保留在那里,我所需要的只是该应用程序内部的会话管理.第一个屏幕也可以正常加载,所以我知道 WebView + 服务器交互性没有中断.
I have an application on appspot that works fine through regular browser, however when used through Android WebView, it cannot set and read cookies. I am not trying to get cookies "outside" this web application BTW, once the URL is visited by WebView, all processing, ids, etc. can stay there, all I need is session management inside that application. First screen also loads fine, so I know WebView + server interactivity is not broken.
我查看了 WebSettings 类,没有像 setEnableCookies 这样的调用.
I looked at WebSettings class, there was no call like setEnableCookies.
我这样加载网址:
public class MyActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webview = new WebView(this);
setContentView(webview);
webview.loadUrl([MY URL]);
}
..
}
有什么想法吗?
推荐答案
我知道发生了什么.
当我通过服务器端操作(url 访问)加载页面,并在 Web 视图中查看从该操作返回的 html 时,第一个操作/页面在该 Web 视图中运行.但是,当您单击网络应用中作为操作命令的任何链接时,这些操作启动新浏览器.这就是 cookie 信息丢失的原因,因为您为 Webview 设置的第一个 cookie 信息消失了,我们这里有一个单独的程序.
When I load a page through a server side action (a url visit), and view the html returned from that action inside a Webview, that first action/page runs inside that Webview. However, when you click on any link that are action commands in your web app, these actions start a new browser. That is why cookie info gets lost because the first cookie information you set for Webview is gone, we have a seperate program here.
您必须拦截对 Webview 的点击,以便浏览永远不会离开应用程序,所有内容都保留在同一个 Webview 中.
You have to intercept clicks on Webview so that browsing never leaves the app, everything stays inside the same Webview.
WebView webview = new WebView(this);
webview.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url); //this is controversial - see comments and other answers
return true;
}
});
setContentView(webview);
webview.loadUrl([MY URL]);
这解决了问题.
这篇关于Android 上的 WebView 和 Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!