Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting Cookies in WebView android

I'm trying to set some cookies on my WebView to open a browser with the same session that I have on my app.

I read a lot of answers but they don't work for me. The only solution I've found is in the loadUrl, hardcode the cookie data in extraHeaders, but as expected this only works for this requests, and doesn't maintain the session.

The code that I have is:

CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(mWebView.getContext());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.removeSessionCookie();
cookieManager.setCookie("http://xx.xxx.example.com","mid="+MySession.GetSession().sessionId+" ; Domain=.example.com");
cookieSyncManager.sync();

String cookie = cookieManager.getCookie("http://xx.xxx.example.com");

Log.d(LOGTAG, "cookie ------>"+cookie);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new TuWebViewClient());
mWebView.loadUrl("http://xx.xx.example.com");

getCookie() returns the correct data, but when I read the cookies from the server, those are empty. What is wrong? Please advise. Thank you!!!

like image 283
flipper83 Avatar asked Mar 22 '11 19:03

flipper83


People also ask

How do I set cookies in WebView?

How do I enable cookies in a webview? CookieManager. getInstance(). setAcceptCookie(true);

Does Android WebView store cookies?

Webview properly, APP has to share cookies with Ms. Webview in the way she prefers, that is through the WebKit CookieManager. The plan is, that every time APP plans to launch Webview, the cookies will need to be copied from the PersistentCookieJar to the CookieManager.


2 Answers

Solved!!!! the problem is with the webView, I dont know what happend, but If I create the

WebView webView = new WebView(Activity.this);

it works. If I read the webview from activity with findViewById() it doesn't work.

Also if you need to set a list of cookies that you received previously from a website. All you have to do is use a for-loop to go through and set all of them . It helped me to solve the situation

like image 186
flipper83 Avatar answered Oct 03 '22 16:10

flipper83


CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(mWebView.getContext());
...
cookieSyncManager.sync();

is the cause of problem. You should do like this:

CookieSyncManager.createInstance(mWebView.getContext());
...
CookieSyncManager.getInstance().sync();

And there will be no need to manually create WebView...

like image 31
Camper Avatar answered Oct 03 '22 18:10

Camper