16

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 .

Tixeon
  • 493
  • 1
  • 4
  • 9

4 Answers4

30

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);
Santacrab
  • 3,165
  • 2
  • 25
  • 31
Tixeon
  • 493
  • 1
  • 4
  • 9
  • up voting since you mention about giving the cookie domain name instead of the server domain that the webview is about to load. this solved my issue – sunil Jan 18 '17 at 04:16
  • @Tixeon could you tell me what libarary i need to inport for this to work ?Android studio keeps complaining about List .Furthermore, can i specifically mention the domain name ?how?Does this saves the cookies and reuse it if when we close and re open the app ? – user1788736 Dec 15 '17 at 20:46
  • 20
    what is WSHelper?? – Adam Kis Jun 01 '18 at 12:39
  • @AdamKis You can get your saved cookies from somewhere else. – chengsam Jun 20 '18 at 08:27
  • not useful at all not mentioned why we can't get List of cookies – HiDd3N Jan 15 '21 at 20:51
3

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);
    }
}
Paul Chu
  • 1,249
  • 3
  • 19
  • 27
Alexiscanny
  • 581
  • 7
  • 15
1

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

voghDev
  • 5,641
  • 2
  • 37
  • 41
1

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.

  • Be sure to answer in the same programming language. The question regards Android Java whereas the answer is for Javascript. However, ideas are welcomed :) – Dimitrios Ververidis Feb 24 '23 at 07:50