Flutter向PHP服务器发起POST请求失败但Postman请求成功的问题求助
Flutter POST请求失败但Postman成功的原因及解决办法
我来帮你分析下这个问题——你遇到的情况很典型,Postman能成功但Flutter代码不行,核心原因是请求体的格式和服务器端的解析方式不匹配。
先看你的代码细节:
- Flutter代码里用了
json.encode()处理请求体,把数据转换成了JSON字符串,但默认情况下http.post不会自动设置正确的Content-Type头(应该是application/json)。 - 你的PHP代码依赖
$_POST获取参数,但**$_POST只负责解析application/x-www-form-urlencoded(表单格式)或multipart/form-data类型的请求体**,完全读不到JSON格式的请求数据,这就导致PHP拿不到quot和teller参数,最终插入操作失败。
而Postman默认发送POST请求时,用的是表单格式(application/x-www-form-urlencoded),所以PHP能正常解析$_POST里的参数,自然就成功了。
下面给你两种可行的解决办法,选一种适合你的即可:
办法一:修改Flutter代码,发送表单格式数据
去掉json.encode(),直接传Map作为body参数,http.post会自动设置Content-Type为application/x-www-form-urlencoded,和Postman的请求格式完全一致:
Future createQuote() async { final response = await http.post( Uri.parse('http://<myserver.com>/quotes/post.php'), body: { 'quot': _quoteController.text, 'teller': _tellerController.text, }, ); if (response.statusCode == 200 && response.body == 'success') { print('s: ' + response.body); // Navigator.pop(context); } else { print(response.body); var test = { 'quot': _quoteController.text, 'teller': _tellerController.text, }; print(test); // throw Exception('Failed to create quote'); } }
办法二:修改PHP代码,解析JSON请求体
如果想继续用JSON格式发送请求,PHP需要读取原始请求体并解析成JSON对象,再提取参数:
require_once('db.php'); // 读取原始请求体内容 $json = file_get_contents('php://input'); // 解析为关联数组 $data = json_decode($json, true); // 先校验请求数据是否合法 if(!$data || !isset($data['quot']) || !isset($data['teller'])){ echo "failure: invalid request data"; exit; } $stm = $db->prepare("INSERT INTO quots (quot, teller) VALUES (:quot, :teller)"); $stm->bindParam(':quot', $data['quot']); $stm->bindParam(':teller', $data['teller']); if ($stm->execute()) { echo "success"; } else { echo "failure: ". $data['quot'] . $data['teller']; };
补充说明:如果选办法二,建议在Flutter代码里手动设置Content-Type头,确保服务器能正确识别请求格式:
Future createQuote() async { final response = await http.post( Uri.parse('http://<myserver.com>/quotes/post.php'), headers: {'Content-Type': 'application/json'}, // 手动指定JSON格式 body: json.encode( { 'quot': _quoteController.text, 'teller': _tellerController.text, }, ), ); // 后续逻辑不变... }
内容的提问来源于stack exchange,提问作者Alexander Roumeliotis
相关产品推荐
相关产品推荐

