Flutter向PHP API发送JSON数组数据的异常排查求助
Flutter向PHP API发送数据时PHP无法获取内容的解决方案
问题根源
Flutter的http.post方法直接传入Map作为body时,默认会将数据编码为application/x-www-form-urlencoded格式,但你的PHP代码是通过file_get_contents("php://input")读取JSON格式的请求体,两者格式不匹配,导致PHP端拿到空数据。
解决方案
以下两种方式任选其一即可:
方式一:修改Flutter端,发送JSON格式数据
修改sendFormDataToApi方法,将Map转为JSON字符串并设置正确的请求头:
// 需在文件顶部导入dart:convert包 import 'dart:convert'; Future<void> sendFormDataToApi(Map<String, dynamic> formData) async { final apiUrl = 'http://kvb-bg.com/Sirena/test_api_adding_devices.php'; try { final response = await http.post( Uri.parse(apiUrl), headers: {'Content-Type': 'application/json'}, // 指定JSON请求头 body: jsonEncode(formData), // 将Map转为JSON字符串 ); if (response.statusCode == 200) { print('Response: ${response.body}'); // 打印响应内容用于调试 } else { throw Exception('Failed to add device'); } } catch (e) { throw Exception('Error: $e'); } }
方式二:修改PHP端,读取form-urlencoded格式数据
如果不想改动Flutter代码,直接让PHP读取POST表单数据:
<?php $requestMethod = $_SERVER['REQUEST_METHOD']; if ($requestMethod === 'POST') { // 直接通过$_POST读取表单字段 $deviceName = isset($_POST['device_name1']) ? $_POST['device_name1'] : ''; $deviceDescription = isset($_POST['device_description1']) ? $_POST['device_description1'] : ''; $deviceCluster = isset($_POST['device_cluster1']) ? $_POST['device_cluster1'] : ''; $deviceGeolocation1 = isset($_POST['device_geolocation11']) ? $_POST['device_geolocation11'] : ''; $deviceGeolocation2 = isset($_POST['device_geolocation21']) ? $_POST['device_geolocation21'] : ''; $sensorWater1Level = isset($_POST['sensor_water_1_level_1']) ? $_POST['sensor_water_1_level_1'] : ''; $sensorWater2Level = isset($_POST['sensor_water_2_level_1']) ? $_POST['sensor_water_2_level_1'] : ''; $sensorWater3Level = isset($_POST['sensor_water_3_level_1']) ? $_POST['sensor_water_3_level_1'] : ''; $sensorLevel1AlertLevel = isset($_POST['sensor_level_1_alert_level_1']) ? $_POST['sensor_level_1_alert_level_1'] : ''; $deviceWiFiName = isset($_POST['device_wifi_network_name1']) ? $_POST['device_wifi_network_name1'] : ''; $deviceWiFiPassword = isset($_POST['device_wifi_network_password1']) ? $_POST['device_wifi_network_password1'] : ''; $deviceMAC = isset($_POST['device_mac1']) ? $_POST['device_mac1'] : ''; } else { http_response_code(400); echo "Unsupported request method"; exit(); } // 数据库连接与操作 $servername = "localhost"; $username = "kvbbgcom_floodPrevention"; $password = "kv0889909595"; $dbname = "kvbbgcom_floodPrevention"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // 打印接收的数据用于调试 echo "Device Name: $deviceName\n"; echo " Device Description: $deviceDescription\n"; echo " Device Cluster: $deviceCluster\n"; echo " Device Geolocation 1: $deviceGeolocation1\n"; echo " Device Geolocation 2: $deviceGeolocation2\n"; echo " Sensor Water 1 Level: $sensorWater1Level\n"; echo " Sensor Water 2 Level: $sensorWater2Level\n"; echo " Sensor Water 3 Level: $sensorWater3Level\n"; echo " Sensor Level 1 Alert Level: $sensorLevel1AlertLevel\n"; echo " Device WiFi Name: $deviceWiFiName\n"; echo " Device WiFi Password: $deviceWiFiPassword\n"; echo " Device MAC: $deviceMAC\n"; // 启用数据库插入时,请使用预处理语句防止SQL注入 // $sql = "INSERT INTO devices (device_name, device_description, device_cluster, device_geolocation_1, device_geolocation_2, sensor_water_1_level, sensor_water_2_level, sensor_water_3_level, sensor_level_1_alert_level, device_wifi_network_name, device_wifi_network_password, device_mac) // VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; // $stmt = $conn->prepare($sql); // $stmt->bind_param("ssssssssssss", $deviceName, $deviceDescription, $deviceCluster, $deviceGeolocation1, $deviceGeolocation2, $sensorWater1Level, $sensorWater2Level, $sensorWater3Level, $sensorLevel1AlertLevel, $deviceWiFiName, $deviceWiFiPassword, $deviceMAC); // if ($stmt->execute()) { // echo "New record created successfully"; // } else { // echo "Error: " . $stmt->error; // } // $stmt->close(); $conn->close(); exit(); ?>
测试验证
- Flutter端点击提交后,查看控制台打印的
Form Data确认数据收集正确 - PHP端可通过
var_dump($_POST);(方式二)或var_dump($input);(方式一)验证数据是否接收成功
内容的提问来源于stack exchange,提问作者Konstantin Violinov
相关产品推荐
相关产品推荐

