Why does Android WebView sporadically not sending my session cookie?
Solution 1:
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();
}
Solution 2:
Thanks Android for ruining my Sunday . . . Heres what fixed my Apps ( after you init your webview )
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ) {
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptThirdPartyCookies( webView, true );
}
I should say the above answers will probably work but in my situation the moment Android went v5+ my android webview javascript 'apps' died.
Solution 3:
Solution:Webview CookieSyncManager
CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(mWebView.getContext());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.removeSessionCookie();
cookieManager.setCookie("http://xx.example.com","mid="+MySession.GetSession().sessionId+" ; Domain=.example.com");
cookieSyncManager.sync();
String cookie = cookieManager.getCookie("http://xx.example.com");
Log.d(LOGTAG, "cookie ------>"+cookie);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new TuWebViewClient());
mWebView.loadUrl("http://xx.example.com");
Solution 4:
the solution is to give the Android enough time to proccess cookies. You can find more information here: http://code.walletapp.net/post/46414301269/passing-cookie-to-webview
Solution 5:
I would save that session cookie as a preference and forcefully repopulate the cookie manager with it. It sounds that session cookie in not surviving Activity restart