[关闭]
@act262 2017-08-10T04:31:06.000000Z 字数 1891 阅读 1476

WebView SslError Mixed Content 问题

webview


出现的问题

WebView 在加载某个地址时发现空白的块(iframe),也就是这块没有加载到
查看logcat的日志:

  1. [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

这个页面使用https协议的,内部嵌入了优酷播放器的iframe,而优酷的URL是http协议的,
也就是https混合http资源等的问题

解决方案

  1. public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
  2. // 默认是handle.cancel()的,即遇到错误即中断
  3. handler.proceed();
  4. }

设置忽略错误后在API 19 (包括KITKAT_WATCH)以前是可以正常看到内容的了,但在API 21+还是空白的。

原来是在API 21以前WebSettings#getMixedContentMode默认返回都是WebSettings.MIXED_CONTENT_ALWAYS_ALLOW,在这之后默认是MIXED_CONTENT_NEVER_ALLOW

所以需要在webview的设置属性中主动设置setMixedContentMode

  1. if (Build.VERSION.SDK_INT >= 21) {
  2. webview.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
  3. }

setMixedContentMode

  1. /**
  2. * Configures the WebView's behavior when a secure origin attempts to load a resource from an
  3. * insecure origin.
  4. *
  5. * By default, apps that target {@link android.os.Build.VERSION_CODES#KITKAT} or below default
  6. * to {@link #MIXED_CONTENT_ALWAYS_ALLOW}. Apps targeting
  7. * {@link android.os.Build.VERSION_CODES#LOLLIPOP} default to {@link #MIXED_CONTENT_NEVER_ALLOW}.
  8. *
  9. * The preferred and most secure mode of operation for the WebView is
  10. * {@link #MIXED_CONTENT_NEVER_ALLOW} and use of {@link #MIXED_CONTENT_ALWAYS_ALLOW} is
  11. * strongly discouraged.
  12. *
  13. * @param mode The mixed content mode to use. One of {@link #MIXED_CONTENT_NEVER_ALLOW},
  14. * {@link #MIXED_CONTENT_ALWAYS_ALLOW} or {@link #MIXED_CONTENT_COMPATIBILITY_MODE}.
  15. */
  16. public abstract void setMixedContentMode(int mode);

使用全站https化后最好是全部资源都https化,避免这种混合的情况出现,因为对安全有所影响,所以GooglePlay市场是不允许这个忽略ssl错误的App上架的。这里忽略错误而继续使用时是一些第三方没有https化无奈的做法,也是迫不得已的。

如果需要考虑安全问题的情况,则要慎重忽略这类错误。

参考:
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

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注