Android - 如何使用webview将cookie传递到加载URL?

时间:2014-03-25 14:22:54

标签: android cookies webview

我必须在webview中加载url并发送一些cookie。你想实现这个目标吗?

我正在做以下代码..

CookieManager cookieManager;

CookieSyncManager.createInstance(PrivacyActivity.this);
cookieManager = CookieManager.getInstance();

cookieManager.setCookie("param", "value");
CookieSyncManager.getInstance().sync();

WebSettings webSettings = wv.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setBuiltInZoomControls(true);
wv.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        return super.shouldOverrideUrlLoading(view, url);
    }
});
wv.loadUrl("https://example.com");

但没有得到正确的结果。刚刚获得" https://example.com"原样。 Cookie不起作用..

2 个答案:

答案 0 :(得分:11)

此解决方案适用于我(只需在加载网址之前将Cookie添加到CookieManager中即可):

WebView webview = (WebView) findViewById(R.id.webview);
...
CookieManager.getInstance().setCookie("http://example.com/", "key=value");
webview.loadUrl("http://example.com/");

答案 1 :(得分:6)

我解决了问题,,,

        WebView webview = (WebView) this.findViewById(R.id.wv_file);
        final WebSettings settings = webview.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setAppCacheEnabled(true);
        settings.setBuiltInZoomControls(true);
        settings.setPluginState(WebSettings.PluginState.ON);

        webview.setWebChromeClient(new WebChromeClient());

        CookieSyncManager.createInstance(ActivityName.this);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeSessionCookie();
        String cookieString = "param=value";
        cookieManager.setCookie(domain_of_url("like http://abc-site.com"), cookieString);
        CookieSyncManager.getInstance().sync();

        Map<String, String> abc = new HashMap<String, String>();
        abc.put("Cookie", cookieString);
        webview.loadUrl("http://abc-site.com/a1/namedFolder/file",
                abc);