android6.0 加载网页图片,android webview 访问https页面图片不显示(5.0+)或显示白页(6.0+)...

在将所有请求切换到HTTPS后,遇到页面显示白屏的问题,原因是WebView不允许混合内容加载。通过设置WebSettings的MixedContentMode为MIXED_CONTENT_ALWAYS_ALLOW允许HTTPS加载HTTP内容,但Android 6.0及以上版本默认会阻止不安全的SSL请求。解决方法是重写WebViewClient的onReceivedSslError方法,使用handler.proceed()接受网站证书。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

总结一下今天的踩的坑

根据项目需要所有请求都换成了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(); // 接受网站证书

}

完事 .好坑

有问题请留言

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值