【发布时间】:2021-03-20 11:37:07
【问题描述】:
我尝试将数据发送到 Web 服务时遇到问题。貌似php文件中的$_POST[]变量没有收到Flutter中http.post请求的body内容。
在 Flutter 中,我使用以下代码:
var url = 'https://www.xxx';
var headers = {
"Content-Type": "application/json",
};
var requestBody = json.encode(
{ 'pays': infoPays, 'societe': infoSociete, });
final http.Response response = await http.post(
url,
body: requestBody,
headers: headers);
print(headers);
print(requestBody);
print(response.statusCode);
我的 php 文件(网络服务)如下:
<?php
//Header
header('Content-type: application/json');
//Connexion à la DB
try {
$bdd = new PDO('xxx');
} catch (\Exception $e) {
die('Erreur : '.$e->getMessage());
}
echo $_POST["pays"];
//Lecture du POST
$pays = isset($_POST["pays"])? htmlspecialchars($_POST["pays"]): "";
$societe = isset($_POST["societe"])? htmlspecialchars($_POST["societe"]): "";
$datetime = date ('Y-m-d H:i:s');
//Insertion des données
$req = $bdd->prepare("INSERT INTO Informations (pays, societe, info_date) values (?,?,?)");
$execute = $req->execute(array($pays, $societe, $datetime));
if ($execute) {
$responseArray = array(
'status' => 'true',
'message' => 'All data have been successfully stored.'
);
} else {
$responseArray = array(
'status' => 'false',
'message' => 'Error happened when storing data.'
);
}
echo json_encode($responseArray);
?>
在我的数据库中,我看到有一条新记录(包括时间戳),我收到一个状态代码 200,证明它可以正常工作,但 php 文件应该从 Flutter http 请求中接收数据(我假设身体)是空的。 没有显示任何内容的 $_POST["pays"] 变量的回声证明了这一点。
因此,php 文件中的 $_POST[ ] 变量似乎没有收到 Flutter 中 http.post 请求正文的内容。
你能帮帮我吗? 我看不出代码有什么问题(我必须承认我不是专业的开发人员)。
非常感谢!
伯纳德
【问题讨论】: