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://mydomain.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);
I magically solved all my cookie problems with this one line in onCreate:
CookieHandler.setDefault(new CookieManager());
edit: it stopped working today. :( what the crap, android.
Solution:Webview CookieSyncManager
I have faced same problem and It will resolve this issue in all android versions
Thanks Android for ruining my Sunday . . . Heres what fixed my Apps ( after you init your webview )
I should say the above answers will probably work but in my situation the moment Android went v5+ my android webview javascript 'apps' died.
Thanks justingrammens! That worked for me, I managed to share the cookie within my DefaultHttpClient requests and WebView activity:
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