WebView常见问题

1. 添加https的证书验证

需要重写WebViewClient中的shouldInterceptRequest方法对请求进行拦截,而且只能对get请求进行验证,post在这里无法获取到请求参数,代码如下:

override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? {
                if (request == null || request.method != "GET") {
                    return null
                } else {
                    val uri = request.url              
                    val urlPath = URL(request.url.toString())
                    val urlConnection = urlPath.openConnection()
                    urlConnection as HttpsURLConnection
                    urlConnection.sslSocketFactory = HttpsUtils.getSSLSocketFactory(R.raw.test)
                    for (entry in request.requestHeaders.entries) {
                            urlConnection.setRequestProperty(entry.key, entry.value)
                        }
                    var contentType = urlConnection.contentType
                    var encoding = urlConnection.contentEncoding
                    val inputStream = urlConnection.getInputStream()
                    return WebResourceResponse(contentType, encoding, inputStream)
                }
            }

而关于

HttpsUtils.getSSLSocketFactory(R.raw.test)

这段代码参考Retrofit使用https

2. 加载url显示的是源代码而不是网页内容

很奇葩的问题,我这里出现这个问题的背景是由于使用了上面所说的https证书验证。去除证书验证一切OK,加上后就会只显示源代码了。通过与正常显示的html进行对比,最后定位到contentType的问题
正常的html:
contentType="text/html"
而显示不正常的html:
contentType="text/html;charset=UTF-8"
而contentEncoding获取的就是编码类型,但通过api获取的却是null,因此重新调整contentType和contentEncoding

var contentType = urlConnection.contentType
var encoding = urlConnection.contentEncoding
val inputStream = urlConnection.getInputStream()
if (contentType != null) {
    contentType = contentType.toLowerCase()
    if (contentType.contains("charset")) {
        if (encoding == null) {
            encoding = contentType.substringAfterLast("=")
            }
        contentType = contentType.substringBeforeLast(";")
     }
}
return WebResourceResponse(contentType, encoding, inputStream)

3. 不能弹出键盘

有些情况下h5的输入框点击后无法弹出键盘,而系统自带的WebView是没问题的。一般出现这种问题是由于系统的双参构造函数为

public WebView(Context context, AttributeSet attrs) {
        this(context, attrs, com.android.internal.R.attr.webViewStyle);
    }

而我的是

public MyWebView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

设置defStyle为com.android.internal.R.attr.webViewStyle问题解决

4. 请求跨域问题

为加快h5的加载,将原本在服务端的h5放在了本地,因此造成了原本能正常发送的请求发不出去了,这是因为出现了跨域问题,原本www.xxx.com/index.html变成了file://xxxxx/index.html,而网络请求的域名依旧是www.xxx.com。为解决跨域问题需要添加如下配置,

webView.settings.allowUniversalAccessFromFileURLs = true

5. 本地html的cookie

与问题4一样,也是h5本地化后出现的问题,原本h5中的请求是有cookie的,本地化后木有了,需要添加如下配置

CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true)

该方法只有在Android 5.0及以上才有效,5.0以下的解决方法暂时还未找到,有知道的小伙伴希望能留个言,谢谢。

发布了37 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/github_34790294/article/details/103750826