简体   繁体   English

WebView.loadUrl(url,headers)在android中不起作用

[英]WebView.loadUrl(url, headers) not working in android

I am setting the cookie in headers and call WebView.loadUrl() with this header but it(Cookie in header) will not work on any android device except 4.4. 我在标头中设置cookie并使用此标头调用WebView.loadUrl()但它(标头中的Cookie)将无法在除4.4之外的任何Android设备上运行。 I have test it on android versions 4.2, 4.3, 4.4, 5.0 and 5.1. 我在Android版本4.2,4.3,4.4,5.0和5.1上测试了它。

webView = (WebView) findViewById(R.id.web_view);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);


HashMap <String, String> extraHeaders = new HashMap<String, String>();
extraHeaders.put("Cookie", "{cookie value}");


webView.setWebViewClient(new WebViewClient() {
    public boolean shouldOverrideUrlLoading(WebView view, String url){
            view.loadUrl(url, extraHeaders);
                return false;
        }
});

webView.loadUrl(url, extraHeaders);

你试过这个吗?

   CookieManager.getInstance().setAcceptCookie(true);

if you are using Android Lollipop, then 如果您使用的是Android Lollipop,那么

CookieManager.getInstance().setAcceptCookie(true);

won't work. 不行。 You need to use 你需要使用

CookieManager.getInstance().setAcceptThirdPartyCookies(true);

To set cookie use the following method 要设置cookie,请使用以下方法

CookieManager.getInstance().setCookie(BuildConfig.BASE_SERVER_ENDPOINT,COOKIE_VAL);

Make sure the base endpoint matches the base url of the links opened in the webview. 确保基本端点与webview中打开的链接的基本URL匹配。

To remove cookie 要删除cookie

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                CookieManager.getInstance().removeAllCookies(null);
            } else {
                CookieManager.getInstance().removeAllCookie();
            }

It's beceause of Cookie Policy, to fix it, you should add this : 这是因为Cookie政策,要修复它,你应该添加:

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    super.init();

    // Allow third party cookies for Android Lollipop
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        WebView webView = (WebView)super.appView;
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptThirdPartyCookies(webView,true);
    }

    super.loadUrl(Config.getStartUrl());
}

This is just a quick post about adding cookies to a web view. 这只是关于将Cookie添加到Web视图的快速帖子。 If you've ever tried to do this the way most people have said that it should be done, you've failed miserably and found this post. 如果你曾经尝试过按照大多数人说应该这样做的方式做到这一点,那你就失败了,发现了这篇文章。 :) :)

The way it's supposed to work is you set the cookie on the CookieManager and then tell the CookieSyncManager to sync. 它应该工作的方式是你在CookieManager上设置cookie然后告诉CookieSyncManager同步。

CookieManager.getInstance().setCookie(domain, value);
CookieSyncManager.getInstance().sync();

I've never got this to work as described. 我从来没有按照描述工作。 With or without async tasks waiting for the threads to catch up. 有或没有异步任务等待线程赶上。

Instead, I just add the cookie in the header of all the loadUrl calls. 相反,我只是在所有loadUrl调用的标头中添加cookie。

Map<String, String> headers = new HashMap<String, String>();
headers.put("Cookie", "cookieName=cookieValue;domain=domain.com;path=/;Expires=Thu, 2 Aug 2021 20:47:11 UTC;");
webView.loadUrl("myurl.com", headers );

Caveat: I only need to initially load the appropriate cookie for the request, if you want to cover nested calls from inside the browser, you need to override shouldOverrideUrlLoading. 警告:我只需要为请求初始加载适当的cookie,如果要覆盖浏览器内部的嵌套调用,则需要覆盖shouldOverrideUrlLoading。

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

If you need to inject the cookie for all requests(including images, js, etc), you're going to need to override shouldInterceptRequest , 如果你需要为所有请求(包括图像,js等)注入cookie,你将需要覆盖shouldInterceptRequest

I got the solution for the issue by creating the custom cookie manager: 我通过创建自定义cookie管理器获得了该问题的解决方案:

public class WebkitCookieManagerProxy extends CookieManager {
    private android.webkit.CookieManager webkitCookieManager;
    public WebkitCookieManagerProxy() {
        this(null, null);
    }
    public WebkitCookieManagerProxy(CookieStore store, CookiePolicy cookiePolicy) {
        super(null, cookiePolicy);
        this.webkitCookieManager = android.webkit.CookieManager.getInstance();
    }
    @Override
    public void put(URI uri, Map<String, List<String>> responseHeaders) throws IOException {
        // make sure our args are valid
        if ((uri == null) || (responseHeaders == null)) return;
        // save our url once
        String url = uri.toString();
        // go over the headers
        for (String headerKey : responseHeaders.keySet()) {
            // ignore headers which aren't cookie related
            if ((headerKey == null) || !(headerKey.equalsIgnoreCase("Set-Cookie2") || headerKey.equalsIgnoreCase("Set-Cookie"))) continue;
            // process each of the headers
            for (String headerValue : responseHeaders.get(headerKey)) {
                this.webkitCookieManager.setCookie(url, headerValue);
            }
        }
    }
    @Override
    public Map<String, List<String>> get(URI uri, Map<String, List<String>> requestHeaders) throws IOException {
        // make sure our args are valid
        if ((uri == null) || (requestHeaders == null)) throw new IllegalArgumentException("Argument is null");
        // save our url once
        String url = uri.toString();
        // prepare our response
        Map<String, List<String>> res = new java.util.HashMap<String, List<String>>();
        // get the cookie
        String cookie = this.webkitCookieManager.getCookie(url);
        if (cookie != null) res.put("Cookie", Arrays.asList(cookie));
        return res;
    }
    @Override
    public CookieStore getCookieStore() {
        // we don't want anyone to work with this cookie store directly
        throw new UnsupportedOperationException();
    }
}

And initialize the custom cookie manager in Application class or when application starts as: 并在Application类或应用程序启动时初始化自定义cookie管理器:

android.webkit.CookieSyncManager.createInstance(this);
android.webkit.CookieManager.getInstance().setAcceptCookie(true);
WebkitCookieManagerProxy coreCookieManager = new WebkitCookieManagerProxy(null, java.net.CookiePolicy.ACCEPT_ALL);
java.net.CookieHandler.setDefault(coreCookieManager);

If you are using Android Lollipop ie SDK 21, then: 如果您使用的是Android Lollipop,即SDK 21,那么:

CookieManager.getInstance().setAcceptCookie(true);

won't work. 不行。 You need to use: 你需要使用:

CookieManager.getInstance().setAcceptThirdPartyCookies(true);

I ran into same issue and the above line worked as a charm. 我遇到了同样的问题,上面的一行充当了魅力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM