Flutter中使用InAppWebView发起HTTP POST请求遇到问题
Flutter InAppWebView HTTP POST 请求失败问题解决
问题背景
在使用Flutter的flutter_inappwebview插件时,WebView内发起的HTTP POST请求无法正常执行,但在WebView外使用http.MultipartRequest实现的相同逻辑可以正常运行。
外部正常执行的POST请求代码
var request = http.MultipartRequest('POST', Uri.parse('你的接口地址')); request.fields.addAll({ 'S2M_SITE': 'xxxxxxxxxx', 'S2M_IDENTIFIANT': 'xxxxxxxxxx', 'S2M_TOTAL': 'xxxxx', 'S2M_REF_COMMANDE': 'xxxxxxxxxx', 'S2M_HTYPE': 'xxxxxxx', 'S2M_DATEH': 'xxxxx', 'S2M_COMMANDE': 'xxxxxx', 'S2M_HMAC': 'xxxxxxx' }); http.StreamedResponse response = await request.send(); if (response.statusCode == 200) { print(await response.stream.bytesToString()); } else { print(response.reasonPhrase); }
错误代码分析
当前WebView POST请求代码存在两个关键问题:
- 请求体格式错误:
application/x-www-form-urlencoded格式要求键值对用=连接,而非代码中使用的: - 多余空格:
S2M_REF_COMMANDE: xxxxxxx中的空格会导致参数解析异常
原错误WebView代码
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("Hello")), body: InAppWebView( initialUrlRequest: URLRequest( url: Uri.parse('你的接口地址'), method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: Uint8List.fromList(utf8.encode( 'S2M_SITE:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' + '&' + 'S2M_IDENTIFIANT:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' + '&' + 'S2M_TOTAL:xxx' + '&' + 'S2M_REF_COMMANDE: xxxxxxx' + '&' + 'S2M_HTYPE: xxxxxx' + '&' + 'S2M_DATEH:xxxxxxx' + '&' + 'S2M_COMMANDE:' + '&' + 'S2M_HMAC:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' )) )) ); }
正确实现示例
修正格式错误后,WebView的POST请求可以正常工作:
@override Widget build(BuildContext context) { // 构建参数Map,避免手动拼接出错 final postParams = { 'S2M_SITE': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 'S2M_IDENTIFIANT': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 'S2M_TOTAL': 'xxx', 'S2M_REF_COMMANDE': 'xxxxxxx', 'S2M_HTYPE': 'xxxxxxx', 'S2M_DATEH': 'xxxxxxx', 'S2M_COMMANDE': '', 'S2M_HMAC': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' }; // 将Map转换为x-www-form-urlencoded格式的字符串 final bodyString = postParams.entries.map((entry) => '${Uri.encodeComponent(entry.key)}=${Uri.encodeComponent(entry.value)}' ).join('&'); return Scaffold( appBar: AppBar(title: const Text("Hello")), body: InAppWebView( initialUrlRequest: URLRequest( url: Uri.parse('你的接口地址'), method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8', }, body: Uint8List.fromList(utf8.encode(bodyString)), ), ), ); }
额外注意事项
- 参数编码:使用
Uri.encodeComponent对键和值分别编码,避免特殊字符导致的解析错误 - Content-Type头:明确指定
charset=utf-8,确保服务端能正确解析请求体 - 空值处理:对于空值参数(如
S2M_COMMANDE),保持键名和等号,值为空即可,无需额外处理
内容的提问来源于stack exchange,提问作者Moustapha Diouf Fall
相关产品推荐
相关产品推荐

