Tixeon
Tixeon

Reputation: 493

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 .

Upvotes: 16

Views: 54601

Answers (4)

Shivaji Jadhav
Shivaji Jadhav

Reputation: 11

Latest way to set cookies using cookieManager

val siteCookies = CookieManager.getInstance().getCookie(“https://www.dummyurl.com”)
cookieManager.removeSessionCookies {
    if (! siteCookies.isNullOrEmpty()) {
        val cookie = siteCookies.split("; ".toRegex())
            .dropLastWhile { it.isEmpty() } as ArrayList<String>
        val iterator = cookie.iterator()
        while (iterator.hasNext()) {
            val cookie = iterator.next()
            if (cookie.isNullOrEmpty()) continue
            cookieManager.setCookie(“https://www.dummyurl.com”, cookie)
        }
    }
}

posting this if this helps someone.

Upvotes: 1

voghDev
voghDev

Reputation: 5801

My problem was slightly different, but answer from @Tixeon gave me the key to solve it. I was composing my Cookie and adding it to the WebView request, but I discovered that Android was overriding my Cookie and sending its own Cookie. So first of all, I had to remove all cookies from the array, then compose my own Cookie. This is the sample code:

// Note that my project has minSdkVersion 21, so I can directly use methods only available in Lollipop
private fun loadUrlInWebView(url: String) {
    webView.settings.apply {
        builtInZoomControls = false
        javaScriptEnabled = true
        useWideViewPort = true
        loadWithOverviewMode = true
        setSupportMultipleWindows(false)
    }
    CookieManager.getInstance().apply {
        setAcceptThirdPartyCookies(webView, true) // My minSdkVersion is 21
        removeAllCookies { value ->
            Log.d("Cookies", "Removed all cookies from CookieManager")
        }
    }

    webView.apply {
        isVerticalScrollBarEnabled = true
        isHorizontalScrollBarEnabled = true
        loadUrl(
            url,
            mutableMapOf(
                "Cookie" to "ThisIsMyCookieWithMyValues",
                "Accept" to "*/*",
                "Accept-Encoding" to "gzip, deflate",
                "Cache-Control" to "no-cache",
                "Content-type" to "application/x-www-form-urlencoded"
            )
        )
    }
}

Now the request contains my Cookie and not the default one provided by Android, and my session in WebView is working. Hope this helps someone else

Upvotes: 1

Tixeon
Tixeon

Reputation: 493

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

Upvotes: 30

Alexiscanny
Alexiscanny

Reputation: 579

Try this code, after few changes works for me:

public class WebViewActivity extends Activity{
    private SharedPreferences mPreferences;

    String token="";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webviewpage);

        mPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);

    }

    public void LaunchWebView(View view) {

        WebView myWebView = (WebView) findViewById(R.id.myWebView);
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.getSettings().setSaveFormData(false);

        CookieSyncManager.createInstance(this);
        CookieSyncManager.getInstance().startSync();
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        CookieManager.getInstance().setAcceptThirdPartyCookies(myWebView, true);

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        String token2= mPreferences.getString("auth_token","");

        HashMap<String, String> map = new HashMap<String, String>();
        map.put("x-auth-token", token);

        myWebView.getSettings().setAppCacheEnabled(true);
        myWebView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view,String url) {
                view.loadUrl(url);
                return true;
            }
        });
        myWebView.loadUrl("YOUR_URL", map);
    }
}

Upvotes: 3

Related Questions