为什么 Android WebView 偶尔不发送我的会话 cookie? [英] Why does Android WebView sporadically not sending my session cookie?

查看:32
本文介绍了为什么 Android WebView 偶尔不发送我的会话 cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务器向我的 android 应用程序发送一个会话 cookie,用于经过身份验证的通信.我正在尝试使用 URL 加载 WebView指向同一台服务器,我正在尝试传入会话 cookie 以进行身份​​验证.我观察到它间歇性地工作,但我不知道为什么.我使用相同的会话 cookie 在我的服务器上进行其他调用,并且这些调用永远不会失败.我只在尝试在 WebView 中加载 URL 时观察到此问题,并且不会每次都发生.非常令人沮丧.

I have a server that sends my android app a session cookie to be used for authenticated communication. I am trying to load a WebView with a URL pointing to that same server and I'm trying to pass in the session cookie for authentication. I am observing that it works intermittently but I have no idea why. I use the same session cookie to make other calls on my server and these never fail authentication. I only observe this problem when trying to load a URL in a WebView, and it does not happen every time. Very frustrating.

以下是我用来执行此操作的代码.任何帮助将不胜感激.

Below is the code that I'm using to do this. Any help will be greatly appreciated.

String myUrl = "http://example.com/"; 
CookieSyncManager.createInstance(this); 
CookieManager cookieManager = CookieManager.getInstance(); 
Cookie sessionCookie =  getCookie(); 
if(sessionCookie != null){ 
    String cookieString = sessionCookie.getName() +"="+sessionCookie.getValue()+"; domain="+sessionCookie.getDomain(); 
    cookieManager.setCookie(myUrl, cookieString); 
    CookieSyncManager.getInstance().sync(); 
} 

WebView webView = (WebView) findViewById(R.id.webview); 
webView.getSettings().setBuiltInZoomControls(true); 
webView.getSettings().setJavaScriptEnabled(true); 
webView.setWebViewClient(new MyWebViewClient()); 
webView.loadUrl(myUrl);

推荐答案

感谢 justingrammens!这对我有用,我设法在我的 DefaultHttpClient 请求和 WebView 活动中共享了 cookie:

Thanks justingrammens! That worked for me, I managed to share the cookie within my DefaultHttpClient requests and WebView activity:

//------- Native request activity
private DefaultHttpClient httpClient;
public static Cookie cookie = null;

//After Login
List<Cookie> cookies = httpClient.getCookieStore().getCookies();
for (int i = 0; i < cookies.size(); i++) {
    cookie = cookies.get(i);
}

//------- Web Browser activity
Cookie sessionCookie = myapp.cookie;
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
if (sessionCookie != null) {
    cookieManager.removeSessionCookie();
    String cookieString = sessionCookie.getName() + "=" + sessionCookie.getValue() + "; domain=" + sessionCookie.getDomain();
    cookieManager.setCookie(myapp.domain, cookieString);
    CookieSyncManager.getInstance().sync();
}   

这篇关于为什么 Android WebView 偶尔不发送我的会话 cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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