WebView未使用Cookie来加载图像

时间:2015-01-07 11:01:42

标签: android cookies webview

当我希望我的WebView加载需要Cookie的图像时,我遇到了麻烦。

我已经在CookieManager'

上设置了我的Cookie
final android.webkit.CookieManager instance = android.webkit.CookieManager.getInstance();
instance.setAcceptCookie(true);
instance.setCookie(".example.fr", mCookies, new ValueCallback<Boolean>() {
    @Override
    public void onReceiveValue(final Boolean value) {
        loadWebView();
    }
});

然后,WebView将加载自定义HTML字符串,因为该应用程序正在生成正确的HTML。

private void loadWebView() {
    // this string is an example of a generated HTML 
    String htmlContent = 
        "<!DOCTYPE html>" +
        "<html><head>" + 
        "<link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen, projection\"/></head>" +
        "<body><img src=\"www.example.fr/img.jpg\"/></body></html>";
    mWebView.loadDataWithBaseUrl("file:///android_asset/", htmlContent, "text/html", "UTF-8", null);
}

我尝试使用Charles Proxy代理网络调用,我注意到www.example.fr/img.jpg的请求在标头中没有设置cookie。但是,当我使用Chrome debbuging检查WebView时,我可以在“资源”选项卡下看到Cookie正确无误。

似乎它们不用于图像下载。

使用Cookie进行资源下载的WebView的任何提示或建议?

谢谢。

1 个答案:

答案 0 :(得分:2)

我遇到了同样的问题,它与以下变化有关: https://developer.android.com/about/versions/android-5.0-changes.html#BehaviorWebView

修复它你需要设置:

CookieManager.getInstance().setAcceptThirdPartyCookies(mWebView,true);