我正在尝试获取我从 Android 中的 JavaScript 代码设置的 cookie。
我已经成功地检查了 Chrome 加载网页时是否成功创建了 cookie,因此我认为它也应该发生在 webview 上。
这是我当前的代码:
webView.loadUrl("http://10.0.2.2:8080/geoserver/www/first_leaflet_webviewer.html");
[…]
String value = getCookie("http://10.0.2.2:8080", "latlng");
getCookie 定义为:
public String getCookie(String siteName,String CookieName){
String CookieValue = null;
CookieManager cookieManager = CookieManager.getInstance();
String cookies = cookieManager.getCookie(siteName);
if(cookies != null){
String[] temp=cookies.split(";");
for (String ar1 : temp ){
if(ar1.contains(CookieName)){
String[] temp1=ar1.split("=");
CookieValue = temp1[1];
}
}
}
return CookieValue;
}
但是 getCookie 总是返回 null,就好像 cookie 从未创建过一样。
我尝试更改http://10.0.2.2:8080对于 http://10.0.2.2:8080/geoserver/www/first_leaflet_webviewer.html和 http://localhost ,以防万一,但无济于事。
我需要更改什么才能读取 cookie?
最佳答案
你能尝试这样设置WebViewClient吗? (请注意,该代码 fragment 是 kotlin。)
webView.webViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
if (CookieManager.getInstance().getCookie(url) != null && CookieManager.getInstance().getCookie(url).contains("latlng")) {
//todo
}
}
override fun onPageFinished(view: WebView, url: String) {
super.onPageFinished(view, url)
if (CookieManager.getInstance().getCookie(url) != null && CookieManager.getInstance().getCookie(url).contains("latlng")) {
//todo
}
}
}
webView.loadUrl("http://10.0.2.2:8080/geoserver/www/first_leaflet_webviewer.html")
关于javascript - Android 无法获取 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60970731/