HTTP POST 请求使用 Flutter 向 PHP REST API 发送



所以我已经这样做太久了,但我只是想不明白为什么这不起作用,我试图做的是将一些 JSON 帖子数据发送到我创建的现有 PHP REST API,然后像$_POST["username"]一样读取该 JSON 数据,我无法真正更改 API 的工作方式,因为它被另一个完美配合的应用程序使用,所以这是要做的事情用我的颤振代码,但我不确定今天开始学习它时是什么。

我的颤振代码:

import 'package:http/http.dart' as http;
http.Response response = await http.post(
'https://path.to.php.file',
headers: <String, String>{
'Content-Type': 'application/json',
},
body: jsonEncode(<String, String>{
"formname": "login",
"username": globals.currentUsername, // value = futurelucas4502
"password": globals.currentPassword, // value = password
"datetime": DateFormat("yyyy-MM-dd HH:mm:ss").format(DateTime.now()) // MySql Datetime format
}),
);
debugPrint("Response: " + response.body);
debugPrint("Status: " + (response.statusCode).toString());

减少PHP代码:

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
echo file_get_contents('php://input');
echo '<br>';
echo $_POST["username"];
?>

输出:

Response: {"formname":"login","username":"futurelucas4502","password":"password","datetime":"2020-05-12 00:01:33"}<br><br />
<b>Notice</b>:  Undefined index: username in <b>/storage/ssd2/545/12156545/public_html/temp/index.php</b> on line <b>7</b><br />
Status: 200

我可以在我的颤振代码中更改什么来使其工作? >EDIT:为了清楚起见,我确实想处理应用程序/json请求,file_get_contents的唯一原因是测试PHP API是否实际接收数据。

看起来你应该只发送一个 urlencode 表单,而不是对帖子数据进行 JSON 编码。

尝试:

body: <String, String>{
"formname": "login",
"username": globals.currentUsername, // value = futurelucas4502
"password": globals.currentPassword, // value = password
"datetime": DateFormat("yyyy-MM-dd HH:mm:ss").format(DateTime.now()) // MySql Datetime format
},

最新更新