Android kotlin 使用原始WebView加载Html代码img标签中oss存储的网络地址图片不显示问题与详细解决办法
在Android Kotlin中使用原始WebView加载HTML代码时,如果标签中的图片是存储在云存储服务(如OSS)中的网络地址,可能会出现图片不显示的问题。下面是一种解决办法:
- 确保在AndroidManifest.xml文件中添加了INTERNET权限:
<uses-permission android:name="android.permission.INTERNET" />
- 在WebView加载HTML代码之前,先设置WebView的WebChromeClient和WebViewClient:
webView.webChromeClient = WebChromeClient()
webView.webViewClient = WebViewClient()
- 创建一个自定义的WebViewClient,并重写shouldInterceptRequest方法:
class CustomWebViewClient : WebViewClient() {
override fun shouldInterceptRequest(
view: WebView?,
request: WebResourceRequest?
): WebResourceResponse? {
val url = request?.url?.toString()
if (url != null && url.startsWith("http")) {
try {
val connection = URL(url).openConnection() as HttpURLConnection
connection.connect()
val inputStream = connection.inputStream
return WebResourceResponse(
connection.contentType,
connection.getHeaderField("encoding"),
inputStream
)
} catch (e: Exception) {
// 处理异常
}
}
return super.shouldInterceptRequest(view, request)
}
}
- 在WebView加载HTML代码之前,将自定义的WebViewClient设置给WebView:
webView.webViewClient = CustomWebViewClient()
- 加载HTML代码:
webView.loadDataWithBaseURL("", htmlCode, "text/html", "UTF-8", "")
这样,WebView就能够正确加载标签中oss存储的网络地址图片了。自定义的WebViewClient会拦截网络请求,并通过URL.openConnection()获取图片的输入流,然后将输入流封装成WebResourceResponse返回给WebView进行加载显示
原文地址: https://www.cveoy.top/t/topic/iI8h 著作权归作者所有。请勿转载和采集!