总结一下今天的踩的坑
根据项目需要所有请求都换成了https,但是我们的图片资源是http的
在后台环境搭建完成后,我发现我的页面是白页!!!
Mixed Content: The page at 'https:xxxxx' was loaded over HTTPS, but requested an insecure image 'http://xxxxxxb95cc58806b3ce0a9.jpg'. This request has been blocked; the content must be served over HTTPS.", source: https:xxxxx
好吧 报了警告.
但是警告也不应该出先白页啊..随后看WebSettings代码
发现
/**
* Used with {@link #setMixedContentMode}
*
* In this mode, the WebView will not allow a secure origin to load content from an insecure
* origin. This is the preferred and most secure mode of operation for the WebView and apps are
* strongly advised to use this mode.
*/
public static final int MIXED_CONTENT_NEVER_ALLOW = 1;
看到了吧 官方强烈推荐使用这种方式
WebView将不允许一个安全的连接混合使用HTTPS +HTTP
这好像5.0以上才有的
因为这个才造成了图片不显示.
所以我们要设置一下
使用下面这个(允许HTTPS +HTTP)
/**
* Used with {@link #setMixedContentMode}
*
* In this mode, the WebView will allow a secure origin to load content from any other origin,
* even if that origin is insecure. This is the least secure mode of operation for the WebView,
* and where possible apps should not set this mode.
*/
public static final int MIXED_CONTENT_ALWAYS_ALLOW = 0;
设置方式
WebSettings wetSettings = webView.getSettings();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
wetSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
但是 貌似还是白页....
这时我的内心是崩溃的,因为 android6.0版本以下正常 ,但是 android6.0版本以上的还是白页
继续寻找原因..然后在
WebViewClient中发现onReceivedSslError方法是这样描述的
/**
* Notify the host application that an SSL error occurred while loading a
* resource. The host application must call either handler.cancel() or
* handler.proceed(). Note that the decision may be retained for use in
* response to future SSL errors. The default behavior is to cancel the
* load.
*
* @param view The WebView that is initiating the callback.
* @param handler An SslErrorHandler object that will handle the user's
* response.
* @param error The SSL error object.
*/
public void onReceivedSslError(WebView view, SslErrorHandler handler,
SslError error) {
handler.cancel();
}
原本方法是当发现ssl加载出现问题时 默认会取消这个请求,就是白页的原因
那就重写WebViewClient的onReceivedSslError方法
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error){
handler.proceed(); // 接受网站证书
}
完事 .好坑
有问题请留言