使用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">