4

I am facing issues with setting cookie in Android WebView. I am using the following code:

CookieSyncManager.createInstance(this); 
CookieManager cookieManager = CookieManager.getInstance(); 
cookieManager.removeAllCookie();    
cookieManager.setAcceptCookie(true);
cookieManager.setCookie(url, cookie); 
CookieSyncManager.getInstance().sync();

But it's not working. I also tried by adding headers using WebView's loadUrl(String url, Map<String, String> additionalHttpHeaders) method; but still it's not working. Is there a way to do this?

althaf_tvm
  • 773
  • 3
  • 15
  • 28
  • Assuming you're trying to pass a cookie from DefaultHttpClient to the WebView, I had the exact same problem yesterday and tried what you tried. This isn't a direct answer to your question, but ultimately what worked for me was fetching the content with DefaultHttpClient and passing the result to the WebView via webView.loadData(htmlString, "text/html", "UTF-8");. Of course this isn't ideal, but is a good enough workaround for now. – ErikR Aug 02 '13 at 16:20
  • Can you paste an example of the cookie String you pass? – qwertzguy Oct 16 '13 at 21:15
  • @althaf_tvm Did you get your solution by any chance? – Hamid Feb 02 '15 at 16:16

2 Answers2

0

Please try this

Cookie sessionCookie = LoginWebView.cookie;
CookieSyncManager.createInstance(webview.this);
CookieManager cookieManager = CookieManager.getInstance();
if (sessionCookie != null) {
    cookieManager.removeSessionCookie();
    String cookieString = sessionCookie.getName();
    Log.v(TAG, "sync cookies: " + cookieString);
    cookieManager.setCookie(domain, cookieString);
    CookieSyncManager.getInstance().sync();
}
Jeremy Logan
  • 47,151
  • 38
  • 123
  • 143
  • 1
    I tried that but still not working. I even added Thread.sleep() for giving some time for cookie manager to set and remove cookies but it didn't work. – althaf_tvm Jun 03 '13 at 06:40
0

The CookieSyncManager is deprecated now, instead use cookieManager.flush(); to update. See this: http://developer.android.com/intl/es/reference/android/webkit/CookieSyncManager.html

Jonathan Aste
  • 1,764
  • 1
  • 13
  • 20