php - 如何向 PHP 服务器发出 post 请求
问题描述
我知道这是一个重复的问题,但我的代码仍然需要帮助。
当我使用邮递员发出发布请求时,它会成功,但是当我使用颤振代码时它会失败。
知道为什么吗?
所以这是发出 post 请求的颤振代码:
Future createQuote() async {
final response = await http.post(
Uri.parse('http://<myserver.com>/quotes/post.php'),
body: json.encode(
{
'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 = jsonEncode(
{
'quot': _quoteController.text,
'teller': _tellerController.text,
},
);
print(test);
// throw Exception('Failed to create quote');
}
}
这是php文件:
require_once('db.php');
$stm = $db->prepare("INSERT INTO quots (quot, teller) VALUES (:quot, :teller)");
$stm->bindParam(':quot', $_POST['quot']);
$stm->bindParam(':teller', $_POST['teller']);
$quot = $_POST['quot'];
$teller = $_POST['teller'];
if ($stm->execute()) {
echo "success";
} else {
echo "failure: ". $_POST['quot'] . $teller;
};
解决方案
不需要jsonEncode
post body,将其用作plain Map
。
final response = await http.post(
Uri.parse('http://<myserver.com>/quotes/post.php'),
body:
{
'quot': _quoteController.text,
'teller': _tellerController.text,
},
);
推荐阅读
- graphql - 你如何在 GraphQL 中处理多个类型的数组(例如:不同的内容块)?
- c - 为什么访问单个 SIMD 元素这么慢
- java - JFrame框架调用JPanelpaintComponent
- c# - 如何在 DataGridView 中显示 LiteDB 数据?
- javascript - 反应和未经许可的参数
- swift - 如何使用“可解码”对象在 Realm 中进行部分更新而不会丢失数据?
- android - 如何使用图像和百分比位置创建 Android 启动画面
- google-app-maker - 关系过滤
- reactjs - 如何在 Material UI/JSS 中定位复杂组件的同级/子级
- api - 在 Postman POST 请求中传递对象列表 -Body