解决Android WebView不显示Mixed Content的问题

场景

在Android中使用WebView加载一些网页时,明明调用了WebView.loadUrl(“xxxxxx”),但是WebView却显示一片空白。

下面是我用WebView加载百度首页(https://www.baidu.com)出现的提示。我用小米手机自带的浏览器加载会弹出证书有问题的提示,但是WebView啥也没提示,只有一片空白。

2019-03-28 12:06:51.973 22181-22181/com.example.app I/chromium: [INFO:CONSOLE(0)] “Mixed Content: The page at ‘https://www.baidu.com/’ was loaded over HTTPS, but requested an insecure image ‘http://d.hiphotos.baidu.com/forum/pic/item/9.jpg’. This request has been blocked; the content must be served over HTTPS.”, source: https://www.baidu.com/ (0)

这个原因是浏览器不允许在https里面嵌套http请求,只要发现https网站中有http请求,直接忽略。

解决方案

最简单的不用https,用http的方式加载网页。但是为了安全肯定不会改成http,所以还是需要设置WebView,
通过以下设置以后,就可以正常加载网页了。

webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

如果是Android 8.0以上,还需要在AndroidManifest.xml中加上以下属性。因为8.0以上默认禁用了http.

<application
    ....
    android:usesCleartextTraffic="true"
    ...>

原理

英文官网
https://developer.android.com/reference/android/webkit/WebSettings.html#setMixedContentMode(int)

国内官网
https://developer.android.google.cn/reference/android/webkit/WebSettings.html#setMixedContentMode(int)


通过文档说明得知,从5.0以后,WebView默认使用的是MIXED_CONTENT_NEVER_ALLOW,也就是不允许从http加载资源,只要改为MIXED_CONTENT_ALWAYS_ALLOW就能正常加载http资源了。

原创文章 65 获赞 26 访问量 10万+

猜你喜欢

转载自blog.csdn.net/adojayfan/article/details/88880269