简体   繁体   中英

Flutter http.post sending empty body

I have a problem when I try to send data to a web service. It seems that the $_POST[ ] variable in the php file doesn't receive the content of the body of the http.post request in Flutter.

In Flutter, I use the following code:

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);

and my php file (web service) is the following:

<?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);
 ?>

In my DB I see that there is a new record (including the time stamp) and I receive a status code 200 proving that it works as it should but the data that the php file is supposed to receive from the Flutter http request (the body, I assume) are empty. It is proven by the echo of the $_POST["pays"] variable that shows nothing.

It seems thus that the $_POST[ ] variable in the php file doesn't receive the content of the body of the http.post request in Flutter.

Could you help me, please? I don't see what's wrong in the code (I must confess I am not a professional developper).

Many thanks !

Bernard

It's something with your php code, the Dart code works fine, as the post request is successful, proven by the new entry in your database.

But since the entry is empty and only has a timestamp, it means that it's not populating your DB fields.

Thus, there is flaw between php and DB, as it is not interpreting or you are not extracting the data correctly. Not a php expert, so can't point out exactly where the problem is, but it's not Flutter\Dart.

I don't see that you are decoding the response from the post body before echoing it or storing it. Decoding the body should help.

Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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