How to set cookie in Android WebView

althaf_tvm picture althaf_tvm · May 29, 2013 · Viewed 8.6k times · Source

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?

Answer

AndroidEnthusiastic picture AndroidEnthusiastic · May 29, 2013

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();
}