Android - 如何传递 cookie 以使用 webview 加载 url?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22637409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:17:20  来源:igfitidea点击:

Android - How to pass cookie to load url with webview?

androidcookieswebview

提问by Mind Android

I have to load url in webview with sending some cookies. HOw to achieve this ?

我必须通过发送一些 cookie 在 webview 中加载 url。如何实现这一目标?

I am doing following code..

我正在做以下代码..

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

But not getting proper result. Just getting "https://example.com" as it is. Cookie does not works..

但没有得到正确的结果。只是按原样获取“ https://example.com”。Cookie 不起作用..

回答by Kata Lune

This solution works for me (Just add cookies to the CookieManager before loading the url and that's all):

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

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

回答by Mind Android

I solved problem as,,,

我解决了问题,,,

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