Reputation: 648
So I have been at this for way way too long but I just can't figure out why this isn't working what I'm trying to do is send some JSON post data to an existing PHP REST API that I've created and then read that JSON data like $_POST["username"]
and I can't really change how the API works as it's used by another application which it works perfectly with so it's something to do with my flutter code but I'm not sure what as I started learning it today.
My flutter code:
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());
Cut down PHP code:
<?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"];
?>
Output:
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
What can I change in my flutter code to make this work?
EDIT: Just for clarity I do want to handle an application/json request the only reason file_get_contents
is there is to test if the PHP API was actually receiving the data.
Upvotes: 0
Views: 5976
Reputation: 51751
It looks like you should just be sending a urlencoded form, rather than JSON encoding the post data.
Try:
body: <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
},
Upvotes: 3