【问题标题】:WebView.loadUrl(url, headers) not working in androidWebView.loadUrl(url,headers)在android中不起作用
【发布时间】:2015-09-21 02:58:43
【问题描述】:

我在标头中设置 cookie 并使用此标头调用 WebView.loadUrl() 但它(标头中的 Cookie)在 4.4 以外的任何 Android 设备上都不起作用。我已经在 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);

【问题讨论】:

    标签: android webview


    【解决方案1】:

    你试过了吗

       CookieManager.getInstance().setAcceptCookie(true);
    

    【讨论】:

      【解决方案2】:

      如果您使用的是 Android Lollipop,那么

      CookieManager.getInstance().setAcceptCookie(true);
      

      行不通。你需要使用

      CookieManager.getInstance().setAcceptThirdPartyCookies(true);
      

      【讨论】:

        【解决方案3】:

        设置cookie使用以下方法

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

        确保基本端点与在 web 视图中打开的链接的基本 url 匹配。

        删除 cookie

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

        【讨论】:

          【解决方案4】:

          这只是一篇关于将 cookie 添加到 Web 视图的快速帖子。如果您曾经尝试过按照大多数人所说的应该这样做的方式来做这件事,那么您就惨遭失败并找到了这篇文章。 :)

          它的工作方式是在 CookieManager 上设置 cookie,然后告诉 CookieSyncManager 进行同步。

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

          我从来没有像描述的那样工作。有或没有等待线程赶上的异步任务。

          相反,我只是在所有 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 );
          

          警告:我只需要为请求加载适当的cookie,如果你想覆盖浏览器内部的嵌套调用,你需要覆盖shouldOverrideUrlLoading。

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

          如果您需要为所有请求(包括图像、js 等)注入 cookie,则需要覆盖 shouldInterceptRequest

          【讨论】:

            【解决方案5】:

            这是因为 Cookie Policy,要修复它,您应该添加以下内容:

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

            【讨论】:

              【解决方案6】:

              我通过创建自定义 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();
                  }
              }
              

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

              【讨论】:

                【解决方案7】:

                如果您使用的是 Android Lollipop,即 SDK 21,那么:

                CookieManager.getInstance().setAcceptCookie(true);
                

                行不通。你需要使用:

                CookieManager.getInstance().setAcceptThirdPartyCookies(true);
                

                我遇到了同样的问题,上面的代码很有魅力。

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 2015-03-18
                  • 2012-05-08
                  • 2019-08-12
                  • 2015-09-12
                  • 2013-10-20
                  • 2015-09-28
                  • 1970-01-01
                  • 2020-12-17
                  相关资源
                  最近更新 更多