跳到正文
Görkem Kara首席移动开发工程师

Android WebView shouldInterceptRequest:进阶用法

阅读约 1 分钟

Android WebView control using shouldInterceptRequest for blocking ads and optimizing data.

shouldInterceptRequest 是 WebViewClient 的一个方法,WebView 发出的每个资源请求(比如图片、脚本和样式)Android 都会调用它。在你自己的 client 中重写它,返回一个 WebResourceResponse,就可以拦截请求、修改请求,或者直接用本地数据响应;返回 null,WebView 就会照常加载资源。下面给出可以直接运行的示例:重定向和修改请求、广告拦截、数据压缩、本地缓存以及添加身份验证请求头。

shouldInterceptRequest 是什么,为什么值得关注?

说到底,shouldInterceptRequest 就像 WebView 所有网络请求的守门人。当 WebView 中的页面尝试获取任何资源(比如图片、脚本或样式)时,shouldInterceptRequest 让你可以拦截这个请求、检查它,并决定是放行、修改还是彻底拦截。

下面是在 CustomWebViewClient 中实现基本 shouldInterceptRequest 的方法:

class CustomWebViewClient : WebViewClient() {
    override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? {
        // Your custom logic goes here
        return super.shouldInterceptRequest(view, request)
    }
}

重定向和修改请求

假设你想加载某个资源的缓存版本,或者重定向一个 URL 来节省流量。用 shouldInterceptRequest,你可以轻松把请求的资源换成另一个。

override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? {
    val url = request?.url ?: return null
    // Serve the logo from the app's assets instead of downloading it again
    if (url.host == "example.com" && url.path == "/images/logo.png") {
        val context = view?.context ?: return null
        return WebResourceResponse(
            "image/png", null,
            context.assets.open("web/logo.png")
        )
    }
    return super.shouldInterceptRequest(view, request)
}

提示:重定向别用得太多。重定向大量请求会拖慢 WebView 的性能,在低端设备上尤其明显。

在 WebView 中拦截广告

说实话,广告无处不在,有时多到让用户体验大打折扣。用 shouldInterceptRequest,你可以根据 URL 拦截这些烦人的广告。

val blockedUrls = listOf("adserver.com", "trackersite.com")
override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? {
    val url = request?.url.toString()
    if (blockedUrls.any { url.contains(it) }) {
        return WebResourceResponse("text/plain", "utf-8", ByteArrayInputStream("".toByteArray()))
    }
    return super.shouldInterceptRequest(view, request)
}

在这个示例中,我们使用一个简单的拦截 URL 列表。如果请求的 URL 与列表中的任意一项匹配,就返回一个空响应,相当于把广告拦截掉了。

数据压缩:节省流量

如果你的 App 要加载大量数据密集的资源,可以在发送前压缩数据来减少流量。下面是设置 gzip 压缩的方法:

override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? {
    val connection = URL(request?.url.toString()).openConnection()
    connection.setRequestProperty("Accept-Encoding", "gzip")

    val inputStream = if (connection.getHeaderField("Content-Encoding") == "gzip") {
        GZIPInputStream(connection.getInputStream())
    } else {
        connection.getInputStream()
    }

    return WebResourceResponse(
        "text/html", "utf-8", inputStream
    )
}

为什么要压缩?

压缩可以节省流量、缩短加载时间,这对流量套餐有限或网络较慢地区的用户非常重要。

在本地缓存资源

假设你希望某些资源只加载一次,然后缓存下来以后再用。这种做法能显著提升性能,尤其是 App 会反复用到同样资源的时候。

override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? {
    val url = request?.url.toString()
    val cachedResponse = getFromCache(url)

    return if (cachedResponse != null) {
        WebResourceResponse("text/html", "utf-8", ByteArrayInputStream(cachedResponse))
    } else {
        super.shouldInterceptRequest(view, request)
    }
}

private fun getFromCache(url: String): ByteArray? {
    // Implement caching logic here
    return null
}

在这个示例中,getFromCache 会尝试从本地存储中获取请求的资源。找到了就返回缓存的响应;否则就让请求照常进行。

添加身份验证请求头

对于需要身份验证的资源(比如 API),可以在请求中加入自定义请求头。方法如下:

override fun shouldInterceptRequest(view: WebView?, request: WebResourceRequest?): WebResourceResponse? {
    val connection = URL(request?.url.toString()).openConnection() as HttpURLConnection
    connection.setRequestProperty("Authorization", "Bearer YOUR_TOKEN")

    val inputStream = connection.inputStream
    return WebResourceResponse(
        "text/html", "utf-8", inputStream
    )
}

在这个示例中,我们给每个请求都加上了 Authorization 请求头。访问受保护的资源时这特别有用。


在 Android WebView 中使用 shouldInterceptRequest,可以为你在 App 内控制、优化和保护网页浏览体验打开很多可能。无论是拦截广告、压缩数据、缓存资源还是添加身份验证,这些技巧都能大幅提升性能和用户体验。多试试这些技巧,定制 WebView 时也别忘了始终把用户体验放在心上。如果你还需要同一个 WebView 中的会话 Cookie,可以看看如何用 Kotlin 从 Android WebView 获取 Cookie。如果你正在开发一个需要在 WebView 中拦截请求、做缓存或加载需要身份验证内容的 App,可以通过联系页面找我做移动应用开发或咨询。

最后更新: 作者: Görkem KARA

#android webview#webview

What did you think of this post?

评论

还没有评论,来写第一条吧。

发表评论

评论经审核后显示。

评论将不显示你的名字发布;邮箱仅用于这条评论,不会公开。 隐私声明

安全验证 发送时自动进行