【问题标题】:CookieManager.getCookie() returns nullCookieManager.getCookie() 返回 null
【发布时间】:2013-03-13 12:20:11
【问题描述】:

我有一些 http 请求。其中之一从它的响应中检索和解析 cookie。我通过 CookieSyncManager 和 CookieManager 使用以下代码保存此 cookie:

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

两个 Log.e 调用写入相同的 cookie。所以一切看起来都很好。

我有不同的活动,其中包含 WebView。我需要使用一些 POST 参数和授权 cookie 调用 postUrl(String url) 方法。我认为 cookie 在 CookieManager 中,一切都应该很好。好吧。它是。但仅限 4.x 设备。

在 2.x 设备上,WebView 使 postUrl 没有 cookie。

这是包含 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) 在 2.x 设备上返回 null,在 4.x 设备上返回 cookie 值。

如何解决这个问题?

【问题讨论】:

    标签: android post cookies webview android-webview


    【解决方案1】:

    看来我发现了问题所在。

    我刚刚删除了

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

    在我保存 cookie 时。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-21
      • 2020-06-19
      相关资源
      最近更新 更多