繁体   English   中英

Flutter http.post 发送空体

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM