You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中Dio与http包POST请求故障排查求助

问题:Flutter项目中Dio GET请求正常,http POST请求无法完成

在Flutter项目中同时使用Dio和http包调用RESTful API,仅fetchData()函数可正常运行,POST请求的addData()功能失效。已尝试多种方案但未解决,附上代码请求排查:

class LoginService {
  final Dio dio = Dio();
  final String baseUrl = 'http://muratkilinc.com/mintsis/web_json.php';
  final url = Uri.parse('http://muratkilinc.com/mintsis/web_json.php');

  Future fetchData() async {
    try {
      final response = await dio.get(baseUrl);
      print(response.statusCode);
      if (response.statusCode == 200) {
        final List<dynamic> responseData = response.data;
        List<DataModel> users = responseData
            .map((userJson) => DataModel.fromMap(userJson))
            .toList();
        print(users);
        print(response.statusCode); //status kodu
      }
    } catch (e) {
      print(e);
    }
  }

  Future<void> addData() async {
    var newUser = {
      "userID": 7,
      "username": "yeni_kullanici",
      "name": "Yeni",
      "surname": "Kullanıcı",
      "password": "e10adc3949ba59abbe56e057f20f883e",
      "typeName": "Öğrenci",
      "departmentName": "Sosyal Hizmet Bölümü"
    };

    try {
      final response = await http.post(
        url,
        headers: {
          "Content-Type": "application/json",
        },
        body: jsonEncode(newUser),
      );
      if (response.statusCode == 200) {
        print("Veri başarıyla eklendi");
      } else {
        print(
            "Veri ekleme işlemi başarısız oldu. StatusCode: ${response.statusCode}");
      }
    } catch (e) {
      print(e);
    }
  }
}

排查方向及解决建议

1. 后端接口参数格式不匹配

很多PHP后端默认接收x-www-form-urlencoded格式,而非JSON。你当前设置的Content-Type是JSON,后端可能无法解析参数。可以尝试修改请求格式:

Future<void> addData() async {
  var newUser = {
    "userID": "7", // 若后端接收字符串类型,转为字符串
    "username": "yeni_kullanici",
    "name": "Yeni",
    "surname": "Kullanıcı",
    "password": "e10adc3949ba59abbe56e057f20f883e",
    "typeName": "Öğrenci",
    "departmentName": "Sosyal Hizmet Bölümü"
  };

  try {
    final response = await http.post(
      url,
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      body: newUser, // 无需jsonEncode,直接传Map
    );
    // 后续逻辑不变
    print("Response body: ${response.body}"); // 新增打印响应内容
  } catch (e) {
    print(e);
  }
}

2. 用Dio发起POST请求排除http包问题

Dio内部会自动处理编码、请求头等细节,和http包的行为可能存在差异。可以尝试用Dio重写addData,看是否能成功:

Future<void> addDataWithDio() async {
  var newUser = {
    "userID": 7,
    "username": "yeni_kullanici",
    "name": "Yeni",
    "surname": "Kullanıcı",
    "password": "e10adc3949ba59abbe56e057f20f883e",
    "typeName": "Öğrenci",
    "departmentName": "Sosyal Hizmet Bölümü"
  };

  try {
    final response = await dio.post(baseUrl, data: newUser);
    if (response.statusCode == 200) {
      print("Veri başarıyla eklendi");
    } else {
      print("Veri ekleme başarısız. StatusCode: ${response.statusCode}, Body: ${response.data}");
    }
  } catch (e) {
    print(e);
  }
}

3. 检查特殊字符编码

参数中包含土耳其语特殊字符(如Öğrenci),http包默认编码可能不兼容,导致参数传递错误。可以尝试手动指定UTF-8编码:

body: utf8.encode(jsonEncode(newUser)),

4. 查看服务器返回的具体错误

在addData中打印完整的响应体,服务器通常会返回具体的错误原因(比如参数缺失、方法不允许等):

print("Response body: ${response.body}");

内容的提问来源于stack exchange,提问作者MertYavuz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 04:32:33