WebView SslError Mixed Content 問(wèn)題
Tags: webview
出現(xiàn)的問(wèn)題
WebView 在加載某個(gè)地址時(shí)發(fā)現(xiàn)空白的塊(iframe),也就是這塊沒(méi)有加載到
查看logcat的日志:
[INFO:CONSOLE(0)] "Mixed Content: The page at 'https://xxx.com' was loaded over HTTPS, but requested an insecure script 'http://player.youku.com/jsapi'. This content should also be served over HTTPS.", source: https://xxx.com/ykplayer
這個(gè)頁(yè)面使用https
協(xié)議的毛俏,內(nèi)部嵌入了優(yōu)酷播放器的iframe纹份,而優(yōu)酷的URL是http
協(xié)議的超埋,
也就是https混合http資源等的問(wèn)題
解決方案
- 重寫(xiě)
WebViewClient
的方法來(lái)忽略這類(lèi)ssl錯(cuò)誤
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
// 默認(rèn)是handle.cancel()的,即遇到錯(cuò)誤即中斷
handler.proceed();
}
設(shè)置忽略錯(cuò)誤后在API 19 (包括KITKAT_WATCH)
以前是可以正澈┑撸看到內(nèi)容的了,但在API 21+
還是空白的。
原來(lái)是在API 21
以前WebSettings#getMixedContentMode
默認(rèn)返回都是WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
,在這之后默認(rèn)是MIXED_CONTENT_NEVER_ALLOW
所以需要在webview的設(shè)置屬性中主動(dòng)設(shè)置setMixedContentMode
if (Build.VERSION.SDK_INT >= 21) {
webview.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
setMixedContentMode
/**
* Configures the WebView's behavior when a secure origin attempts to load a resource from an
* insecure origin.
*
* By default, apps that target {@link android.os.Build.VERSION_CODES#KITKAT} or below default
* to {@link #MIXED_CONTENT_ALWAYS_ALLOW}. Apps targeting
* {@link android.os.Build.VERSION_CODES#LOLLIPOP} default to {@link #MIXED_CONTENT_NEVER_ALLOW}.
*
* The preferred and most secure mode of operation for the WebView is
* {@link #MIXED_CONTENT_NEVER_ALLOW} and use of {@link #MIXED_CONTENT_ALWAYS_ALLOW} is
* strongly discouraged.
*
* @param mode The mixed content mode to use. One of {@link #MIXED_CONTENT_NEVER_ALLOW},
* {@link #MIXED_CONTENT_ALWAYS_ALLOW} or {@link #MIXED_CONTENT_COMPATIBILITY_MODE}.
*/
public abstract void setMixedContentMode(int mode);
使用全站https
化后最好是全部資源都https
化杠茬,避免這種混合的情況出現(xiàn)琳拨,因?yàn)閷?duì)安全有所影響瞭恰,所以GooglePlay
市場(chǎng)是不允許這個(gè)忽略ssl錯(cuò)誤的App上架的。這里忽略錯(cuò)誤而繼續(xù)使用時(shí)是一些第三方?jīng)]有https化無(wú)奈的做法狱庇,也是迫不得已的惊畏。
如果需要考慮安全問(wèn)題的情況恶耽,則要慎重忽略這類(lèi)錯(cuò)誤。
參考:
https://stackoverflow.com/questions/28626433/android-webview-blocks-redirect-from-https-to-http
https://stackoverflow.com/questions/31509277/webview-images-are-not-showing-with-https