有天被问到WebView加载网页404替换的问题,想了一种方法,记录如下:
思路就是先获取请求返回的状态码,判断状态码是404,就加载404的网页
这里的404效果用的简书404的地址,可以替换成自己的404即可
代码如下:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initWebViewSetting(my_webview)
btn404.setOnClickListener {
loadUrl("https://www.baidu.com/12/143")
}
btnNormal.setOnClickListener {
loadUrl("https://www.baidu.com")
}
}
fun initWebViewSetting(webView: WebView) {
with(webView.settings) {
javaScriptEnabled = true
setSupportZoom(true)
useWideViewPort = true
domStorageEnabled = true
loadWithOverviewMode = true
layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
}
}
fun loadUrl(url: String) {
val okhttp = OkHttpClient()
val request = Request.Builder().url(url)
.build()
okhttp.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
}
override fun onResponse(call: Call, response: Response) {
val body = response.newBuilder().build()
if (body.code() == 404) {
runOnUiThread {
my_webview.stopLoading()
my_webview.loadUrl("https://www.jianshu.com/404")
}
} else if (body.isSuccessful) {
val html = body.body()?.string()
runOnUiThread {
my_webview.stopLoading()
// my_webview.loadDataWithBaseURL(
// "https://www.baidu.com/",
// html!!,
// "text/html",
// "utf-8", null
// )
my_webview.loadUrl(url)
}
}
}
})
}
}
先使用okhttp请求网址,判断返回状态码,如果状态码是404,加载404网页,如果是成功,再用webView加载此网址,缺点就是请求了两次网页。也可以尝试使用loadDataWithBaseURL直接加载okhttp返回的网页。