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

使用WebView加载一些Htpps的网页时,明明调用了WebView.loadUrl(“xxxxxx”),但是发现内容展示不全,或存在问题。并且Logcat中会出现一些报错:

“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请求,直接忽略。

解决方案

因为在Android 5.0以后,WebView默认使用的是MIXED_CONTENT_NEVER_ALLOW,也就是不允许从http加载资源,只要改为MIXED_CONTENT_ALWAYS_ALLOW就能正常加载http资源了。解决这个问题只需对WebView增加以下设置:

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

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

<application android:usesCleartextTraffic="true">

注意:在安全要求等级高的的App或者组件内,不要轻易加此配置,而是应该驱动提供Web页面的人将所有的内容都替换为Https的内容。

posted @ 2021-09-01 17:22  灰色飘零  阅读(893)  评论(0编辑  收藏  举报