Cookies & Webview - CookieSyncManager in Android!

2019-01-24 08:27发布

问题:

I have an activity that lets you sign in to a page. In the next activity it should display a webpage based on the cookie if the login was successful. The cookie is retrived and I try to put it on the webView with the following code:

    Cookie sessionCookie = LoginWebView.cookie;
    CookieSyncManager.createInstance(webview.this);
    CookieManager cookieManager = CookieManager.getInstance();
    if (sessionCookie != null) {
                        cookieManager.removeSessionCookie();
        String cookieString = sessionCookie.getName() + "=" + sessionCookie.getValue() + "; domain=" + sessionCookie.getDomain();
        Log.v(TAG, "COOKIE SYNC: " + cookieString);
        cookieManager.setCookie(domain, cookieString);
        CookieSyncManager.getInstance().sync();

    }

    webView.setWebViewClient(new MyWebViewClient ());
    webView.loadUrl("http://a_page.com/getpageiphone.aspx?p=home");

This is losely based on code from other questions here on StackOverflow, but when I load the web-page it does not seem to work. It seems as there is something very wrong with my code but I can't see where and I'm starting to think I'm doing something very wrong.

回答1:

You have used this line -

 if (sessionCookie != null) {
                          cookieManager.removeSessionCookie();

  }

. To ensure you receive new cookie everytime.

Seems like you have gone through same issue as I faced, check below link -

removeSessionCookie() issue of android (code.google.com)

it says that removeSessionCookie() is implemented in a thread, so whenever it is called; a thread starts and after your setCookie(url, cookieString); is called, it removes the new cookie you just set. So for some devices it works well as removeSessionCookie() is already executed, while, for some, it remove the cookie, and we get that problem.

by using SystemClock.sleep(500); , you just gave system to finish removeSessionCookie() first

I suggest you remove this removeSessionCookie(); as you are setting only one cookie, so it won't conflict with other cookies. Your code will work seamlessly.



回答2:

First of all, make sure to read the header values that your website gives you. You can determine this via Wireshark.

Secondly, when you know how the cookie look like (based from your Wireshark values), you should try to achieve the same values in your code. Make sure to debug the cookie's value(s) and make adjustments on the cookie itself if it doesn't match.