Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set cookie in android WebView client

I want to call one specific url via WebView. The page can only be called after user already logged in. I use AsyncHttpClient library to perform login call. Once after successfully logged in , loading url via WebView doesn't seem recognise the proper headers esp cookie. My suspect is that cookies are not sync correctly between HttpClient and WebView's HttpClient . Any idea why ? . Here is how i use WebView

    final WebView webView = (WebView) content.findViewById(R.id.web_travel_advisory);
    String url = "http://mydomainurl.com/get_data_after_login";

    webView.setWebViewClient(new WebViewClient());

    CookieSyncManager.createInstance(getActivity());
    CookieSyncManager.getInstance().startSync();
    CookieManager.getInstance().setAcceptCookie(true);

    webView.getSettings().setJavaScriptEnabled(true);

    webView.loadUrl(url);

Appreciate ur help .

like image 206
Tixeon Avatar asked Oct 14 '15 08:10

Tixeon


People also ask

How do I set cookies in WebView?

It's quite simple really. String cookieString = "cookie_name=cookie_value; path=/"; CookieManager. getInstance(). setCookie(baseUrl, cookieString);

How do I enable cookies on Android WebView?

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

Do cookies work in WebView?

Bookmark this question. Show activity on this post. I have an application on appspot that works fine through regular browser, however when used through Android WebView, it cannot set and read cookies.

Does Android WebView store cookies?

WebViews automatically persist cookies into a android. webkit. CookieManager. Need to store cookies from a WebView into a java.


1 Answers

Ohh after several hours, i finally figured it out to get it worked. Firstly CookieSyncManager is deprecated on later version of android since api 21 according to doc. So decided not to use it anymore. Secondly CookieManager is used to store cookie for WebView.

Final code

    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(true);

    List<Cookie> cookies = WSHelper.cookieStore.getCookies();

    cookieManager.removeAllCookie();

    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().contains("session")){
                String cookieString = cookie.getName() + "=" + cookie.getValue() + "; Domain=" + cookie.getDomain();
                cookieManager.setCookie(cookie.getDomain(), cookieString);
                Log.d("CookieUrl",cookieString + " ");
            }
        }
    }
    webView.loadUrl(url);

The key changes to solution is: use cookie.getDomain() instead of explicit domain.

cookieManager.setCookie(cookie.getDomain(), cookieString);
like image 193
Tixeon Avatar answered Oct 12 '22 04:10

Tixeon