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

Flutter中POST请求如何正确发送含数组的JSON请求体?

问题原因

你直接把jsonMap传给http.post的body参数时,Flutter的http库会默认把数据编码成application/x-www-form-urlencoded(表单格式),这种格式无法正确传递数组类型的数据,服务器自然解析不了你的goals列表。而Postman里你是直接发送JSON格式的请求体,所以能正常工作。

解决方法

要发送JSON格式的请求体,需要两步:

  • 用json.encode()把你的Map转换成JSON字符串
  • 设置请求头的Content-Type为application/json,明确告诉服务器接收的是JSON数据

修改后的代码如下:

import 'dart:convert'; // 必须导入这个包才能使用json.encode

// 确保programGoals是List<String>类型
List<String> programGoals = ["goal1", "goal2", "goal3"];

Map<String, dynamic> jsonMap = {
  "title": itemTitle,
  "description": itemDescription,
  "category": category,
  "imageCover": "",
  "author": "",
  "authorImageProfile": "",
  "dayCount": "10",
  "goals": programGoals
};

final response = await http.post(
  Uri.parse('$localHost$url'),
  headers: {'Content-Type': 'application/json'}, // 新增请求头
  encoding: Encoding.getByName('utf-8'),
  body: json.encode(jsonMap), // 将Map转为JSON字符串
);
额外注意
  • 务必导入dart:convert包,否则json.encode会报错
  • 确认programGoals是List<String>类型,避免因类型不匹配导致JSON编码失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 15:59:51