[英]Flutter http.post sending empty body
當我嘗試向 web 服務發送數據時遇到問題。 php 文件中的 $_POST[ ] 變量似乎沒有收到 Flutter 中 http.post 請求的正文內容。
在 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 Z80791B3AE7002CB88888Z4 請求接收到的數據,我假設)是空的。 沒有顯示任何內容的 $_POST["pays"] 變量的回聲證明了這一點。
因此,php 文件中的 $_POST[] 變量似乎沒有收到 Flutter 中的 http.post 請求的正文內容。
請問你能幫幫我嗎? 我看不出代碼有什么問題(我必須承認我不是專業的開發人員)。
非常感謝 !
伯納德
這與您的 php 代碼有關,Dart 代碼工作正常,因為發布請求成功,數據庫中的新條目證明了這一點。
但是由於該條目是空的並且只有一個時間戳,這意味着它沒有填充您的數據庫字段。
因此,php 和 DB 之間存在缺陷,因為它沒有解釋或者您沒有正確提取數據。 不是 php 專家,所以不能准確指出問題出在哪里,但不是 Flutter\Dart。
我沒有看到您在回顯或存儲它之前正在解碼來自帖子正文的響應。 解碼身體應該會有所幫助。
干杯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.