【发布时间】:2020-08-27 15:52:24
【问题描述】:
所以我在这方面已经太久了,但我只是不明白为什么这不起作用我正在尝试做的是将一些 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
我可以在我的颤振代码中进行哪些更改以使其正常工作?
编辑:为了清楚起见,我确实想处理应用程序/json 请求,file_get_contents 的唯一原因是测试 PHP API 是否实际接收数据。
【问题讨论】:
-
你不能只在你的 php 脚本中获取用户名值,对吗?
-
PHP 代码相当混乱。您要处理
application/json请求还是application/x-www-form-urlencoded?file_get_contents('php://input')建议前者,但$_POST["username"]建议后者。你不能两者兼得。这个其他应用程序使用什么? -
我想使用 application/json 和 $_POST["username"] 但谢谢我现在有一个解决方案