Flutter中通过InAppWebView拦截Post请求并获取请求体的问题
Flutter InAppWebView 安卓端拦截POST请求并获取请求体方案
问题分析
iOS端通过shouldOverrideUrlLoading可以正常拦截POST请求,但安卓端该方法仅处理GET类跳转请求,无法捕获POST;shouldInterceptFetchRequest仅覆盖Fetch API发起的请求,且无法获取请求体。
解决方法
利用安卓端专属的androidOnShouldInterceptRequest回调,可完整捕获包括表单提交、XHR、Fetch在内的所有POST请求,并读取请求体:
InAppWebView( initialUrlRequest: URLRequest(url: Uri.parse("你的目标页面地址")), // 安卓端请求拦截回调 androidOnShouldInterceptRequest: (controller, request) async { // 匹配目标POST请求 if (request.method == "POST" && request.url.toString().contains("你的目标接口路径")) { // 读取并解析请求体 if (request.body != null) { String requestBody = utf8.decode(request.body!); // 这里处理获取到的请求体,比如打印、存储等 print("捕获到POST请求体:$requestBody"); } } // 返回null表示不中断请求,继续正常加载 return null; }, // 安卓端基础配置(确保拦截权限) androidSettings: AndroidSettings( allowContentAccess: true, allowFileAccess: true, ), )
关键说明
androidOnShouldInterceptRequest对应安卓原生WebView的shouldInterceptRequest方法,支持获取所有类型HTTP请求的完整信息,包括POST请求体。- 若使用的是InAppWebView 6.x及以上版本,组件形式可能改为
WebViewWidget,但androidOnShouldInterceptRequest配置逻辑一致。 - 确保依赖的
flutter_inappwebview包是最新版本,旧版本可能存在请求体读取异常的问题。
内容的提问来源于stack exchange,提问作者navi95
相关产品推荐
相关产品推荐

