1

I have some http requests. One of them retrieves and parse cookie from it's response. I save this cookie via CookieSyncManager and CookieManager with following code:

CookieSyncManager.createInstance(context);
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.removeSessionCookie();
            cookieManager.removeAllCookie();
            String cookieString = cookie.getName() + "=" + cookie.getValue();
            Log.e(getClass().toString(), cookieString);
            cookieManager.setCookie(START_PAYMENT_URL, cookieString);
            CookieSyncManager.getInstance().sync();
            Log.e(getClass().toString(), "Get cookie: " + cookieManager.getCookie(START_PAYMENT_URL));

Both Log.e calls write same cookie. So everything looks ok.

I have different activity which contains WebView. I need to call postUrl(String url) method with some POST params and with authorization cookie. I thought that cookie is in CookieManager and everything should work great. Well. It is. But on 4.x devices only.

On 2.x devices WebView makes postUrl without cookie.

Here is activity code which contains WebView:

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.payment_webview);

        final String billId = getIntent().getStringExtra(INTENT_BILL_ID);

        final WebView webView = (WebView) findViewById(R.id.payment_webview);

        webView.getSettings().setJavaScriptEnabled(true);

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.e(getClass().toString(), url);
                view.loadUrl(url);
                return false;
            }
        });

        String postData = "id_bill=" + billId;
        Log.d(TAG, "Requesting payment URL " + START_PAYMENT_URL + " with post data: " + postData);
        Log.d(TAG, CookieManager.getInstance().getCookie(START_PAYMENT_URL));
        webView.postUrl(START_PAYMENT_URL, EncodingUtils.getBytes(postData, "BASE64"));
    }

CookieManager.getInstance().getCookie(START_PAYMENT_URL) returns null on 2.x devices and cookie value on 4.x devices.

How to fix this problem?

4

1 回答 1

0

似乎我弄清楚了问题所在。

我刚刚删除

cookieManager.removeSessionCookie();
cookieManager.removeAllCookie();

当我保存饼干时。

我想这个问题是所有的CookieManager工作方法都是异步的。可能会删除之后调用的 cookie 方法,cookieManager.setCookie(START_PAYMENT_URL, cookieString);即使它们在它之前调用也是如此。因此CookieManager保存 cookie,然后删除调用的 cookie 方法。

于 2013-03-14T04:06:34.683 回答