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

Flutter中POST请求返回400 Bad Request错误,求排查原因

问题原因及解决方案

核心问题

Postman中请求体是数组包裹的单个对象,但你的Flutter代码直接发送了单个JSON对象,格式不匹配导致服务器无法解析,返回400错误。

Postman请求体结构:

[
  { 
    "athleteId":"16198",
    "departmentId":"3",
    "teamId":"278"
  }
]

你的Flutter代码生成的请求体结构:

{
  "athleteId": 16198,
  "departmentId": 3,
  "teamId": 278
}

修改后的代码

将请求体包裹在数组中,同时如果服务器要求ID为字符串类型,需将int转成String:

static Future<List<Athlete>> insertPresences(
      int athleteId, int departmentId, int teamId) async {
    try {
      final response = await http.post(
        Uri.parse('https://my_domain/path'),
        headers: <String, String>{
           'Authorization': 'Basic ..',
          'Content-Type': 'application/json; charset=UTF-8',
          'Accept': 'application/json'
        },
        // 包裹为数组结构,若服务器要求字符串ID则调用toString()转换
        body: jsonEncode([
          {
            "athleteId": athleteId.toString(),
            "departmentId": departmentId.toString(),
            "teamId": teamId.toString()
          }
        ]),
      );
      print('Response status: ${response.statusCode}');
      print('Response body: ${response.body}');

      if (response.statusCode == 201) {
        List jsonResponse = json.decode(utf8.decode(response.bodyBytes));

        return jsonResponse
            .map((_insert) => Athlete.fromJson(_insert))
            .toList();
      }
    } catch (e) {
      logger.e(e.toString());
    }
    return insertPresences(athleteId, departmentId, teamId);
  }

额外检查项

  • 确认Authorization头的内容和Postman中完全一致
  • 如果修改数组结构后仍报错,优先排查ID的数据类型是否和服务器要求匹配(Postman中是字符串,原代码为int)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 19:40:59