通过WebView打开网页时,WebView会在请求头中自动添加x-requested-with
字段,字段值为应用的包名。
本文介绍如何修改x-requested-with的值。
查看请求头
为了方便调试,可以使用Chrome Inspect工具来调试WebView加载的网页。
- 配置WebView开启调试模式,代码如下:
WebView.setWebContentsDebuggingEnabled(true)
- 手机开启开发者模式,连接电脑,使用Chrome浏览器或Edge浏览器,打开Inspect网页。
// Chrome 浏览器
chrome://inspect/#devices
// Edge 浏览器
edge://inspect/#devices
- 选择想要调试的网页,点击inspect。
- 在打开的Inspect窗口中点击网络查看请求头 。
修改x-requested-with
- 通过loadUrl修改
在加载网页时,配置请求头进行修改,代码如下:
webview.loadUrl("https://juejin.cn/", mapOf(Pair("x-requested-with", "")))
效果如图:
通过loadUrl加载的链接
链接网页内部的其他请求
可以看到,此方式只对通过loadUrl加载的链接生效,链接网页内部其他请求的x-requested-with没有被修改。
- 通过获取包名方法修改
找到另一个解决方案,在Application
找到WebView获取包名的方法,修改返回值,代码如下:
class ExampleApplication : Application() {
override fun getPackageName(): String {
try {
val stackTrace = Thread.currentThread().stackTrace
for (item in stackTrace) {
if ("org.chromium.base.BuildInfo".equals(item.className, true)) {
if ("getAll".equals(item.methodName, true)) {
return ""
}
}
}
} catch (e: Exception) {
e.printStackTrace()
}
return super.getPackageName()
}
}
// 在manifest中配置自定义的application
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:name=".base.ExampleApplication"
.../>
</manifest>
效果如图:
通过这种方式,所有请求的x-requested-with都会被修改。