首页 > 解决方案 > 如何向 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;
};

标签: phpmysqlflutterdartpost

解决方案


不需要jsonEncodepost body,将其用作plain Map

    final response = await http.post(
      Uri.parse('http://<myserver.com>/quotes/post.php'),
      body: 
        {
          'quot': _quoteController.text,
          'teller': _tellerController.text,
        },
    );

推荐阅读