Flutter中如何处理WebView内发起请求的JSON响应?
处理flutter_inappwebview中/api/v1/fetch接口的JSON响应
直接使用InAppWebView组件的shouldInterceptRequest回调即可实现拦截并处理目标接口的响应,以下是具体实现方案:
核心实现代码
import 'dart:convert'; import 'dart:typed_data'; import 'package:flutter_inappwebview/flutter_inappwebview.dart'; import 'package:http/http.dart' as http; // 在你的页面Widget中使用 InAppWebView( initialUrlRequest: URLRequest(url: Uri.parse("你的网页地址")), shouldInterceptRequest: (controller, request) async { // 匹配目标接口路径 final requestUrl = request.url.toString(); if (requestUrl.contains("/api/v1/fetch")) { // 根据请求方法发起对应请求获取原始响应 late http.Response httpResponse; if (request.method == "GET") { httpResponse = await http.get(request.url, headers: request.headers); } else if (request.method == "POST") { // 处理POST请求的body final body = request.body; httpResponse = await http.post( request.url, body: body, headers: request.headers, ); } // 解析并处理JSON响应 if (httpResponse.headers["content-type"]?.contains("application/json") ?? false) { Map<String, dynamic> originalData = jsonDecode(httpResponse.body); // 这里添加你的自定义处理逻辑,比如修改字段、过滤数据 originalData["custom_field"] = "processed_by_flutter"; // 将处理后的数据转为字节流 final processedBody = jsonEncode(originalData); final data = Uint8List.fromList(processedBody.codeUnits); // 返回处理后的响应给WebView return WebResourceResponse( data: data, mimeType: "application/json", encoding: "utf-8", statusCode: httpResponse.statusCode, reasonPhrase: httpResponse.reasonPhrase, headers: httpResponse.headers.map((key, value) => MapEntry(key, value.join(","))), ); } } // 非目标请求,返回null让WebView正常处理 return null; }, )
注意事项
- 确保添加
http包到项目依赖中(在pubspec.yaml里声明对应版本) - 如果接口有复杂的请求头、Cookie或者证书验证需求,需要在自定义请求时同步处理
- 若遇到跨域问题,由于是Flutter端发起请求而非WebView,无需额外配置CORS(除非接口本身限制请求来源)
内容的提问来源于stack exchange,提问作者kokoko
相关产品推荐
相关产品推荐

