Flutter篇 http设置“content-type“: “application/json“会出现报错Cannot set the body fields of a Request ...

在Flutter里,HTTP请求发送时设置'content-type': 'application/json'会报错'Cannot set the body fields of a Request with content-type “application/json”',解决办法是通过jsonEncode处理要提交的参数。

在flutter中在http请求发送时设置"content-type": "application/json"会出现报错Cannot set the body fields of a Request with content-type “application/json”

 

解决方法

通过jsonEncode处理要提交的参数

final putData = jsonEncode(params);    // 处理提交参数
final putResponse = await http.put('http://192.168.201.21/user/modifyUser',
    body: putData,
    headers: {"token": userBasicsInfo.userTokenResult,"content-type": "application/json"}
).then((response){
  var backResult;
  if(response.statusCode == 200){
   。。。。。。
  }else{
    print('数据请求错误:${response.statusCode}');
  }
  return backResult;
});

 

你遇到的问题有两个: --- ## ❌ 问题分析 ### 🔴 错误 1:`JSON parse error - Expecting property name enclosed in double quotes` > 这说明 **后端收到的 JSON 数据格式不合法** ### 🔴 错误 2:`curl: (3) URL rejected: Malformed input to a URL function` > 这是 PowerShell 中 `curl.exe` 对换行符和引号处理不当导致的语法错误 --- ## ✅ 正确解决方案 ### ✅ 方法一:使用单行命令(推荐) 避免使用反引号 `\` 换行,直接写成一行: ```powershell curl.exe -X POST http://127.0.0.1:8000/api/chat/ -H "Content-Type: application/json" -d "{\"message\": \"福州鱼丸是什么做的?\"}" ``` 📌 注意: - 所有内容在**同一行** - 使用 `\"` 转义双引号 - `-d` 后面紧跟数据,不要换行 ✅ 成功示例输出(假设 API 正常): ```json {"reply": "福州鱼丸选用鳗鱼或鲨鱼肉打成浆,加入地瓜粉搅拌上劲,挤成丸子下锅煮熟……"} ``` --- ### ✅ 方法二:使用变量存储 JSON(更安全) ```powershell # 定义 JSON 字符串 $body = '{\"message\": \"福州鱼丸是怎么做的?\"}' # 发送请求 curl.exe -X POST http://127.0.0.1:8000/api/chat/ ` -H "Content-Type: application/json" ` -d $body ``` 这种方式可以避免引号混乱。 --- ### ✅ 方法三:使用 Python 的 `requests` 测试(最稳定) 如果你觉得 `curl` 麻烦,可以直接用 Python 脚本测试: ```python # test_chat.py import requests url = "http://127.0.0.1:8000/api/chat/" data = {"message": "福建有什么非遗美食?"} response = requests.post(url, json=data) # 自动设置 Content-Type 并序列化 JSON print("状态码:", response.status_code) print("响应:", response.json()) ``` 运行: ```bash python test_chat.py ``` ✅ 输出示例: ```text 状态码: 200 响应: {'reply': '福建的小吃丰富多彩,代表性有福州鱼丸、泉州土笋冻、厦门沙茶面……'} ``` --- ## 🛠️ 前端注意:发送 JSON 的正确方式 无论你是用 JS、Flutter 还是 Android 发送请求,请确保: ```javascript fetch('http://127.0.0.1:8000/api/chat/', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ message: "福州鱼丸怎么做?" }) }) .then(res => res.json()) .then(console.log); ``` ⚠️ 不要发送字符串 `"\"{message: ...}\""`,必须是合法 JSON--- ## 🔍 为什么会出现 `Expecting property name enclosed in double quotes`? 这是 Python 内部 `json.loads()` 报错,意味着它收到了类似这样的字符串: ```text {message: "你好"} ← 错误!key 没有双引号 "{\"message: ...}" ← 转义错了,变成字符串了 '{ "message": "..." }' ← 单引号不是标准 JSON ``` 只有下面这个才是合法 JSON: ```json {"message": "福州鱼丸是什么做的?"} ``` --- ## ✅ 最终建议:修改视图增加容错提示 你可以临时增强你的 `chat_with_ai` 视图来帮助调试: ```python @api_view(['POST']) def chat_with_ai(request): # 调试:打印原始请求体(仅开发环境) try: user_message = request.data.get('message', '').strip() except Exception as e: return Response( {'error': f'无效的 JSON 格式,请发送如 {{"message": "你的问题"}}', 'detail': str(e)}, status=status.HTTP_400_BAD_REQUEST ) if not user_message: return Response( {'error': '消息内容不能为空'}, status=status.HTTP_400_BAD_REQUEST ) # 其余逻辑不变... ``` 这样前端就知道哪里错了。 --- ## ✅ 总结:如何避免这个问题 | 措施 | 说明 | |------|------| | ✅ 使用单行 `curl` 命令 | 避免 PowerShell 换行符问题 | | ✅ 用 `json=data` 而不是 `data=json.dumps(...)` | 在 Python 中用 `requests.post(url, json=...)` | | ✅ 确保 JSON key 用双引号 | `"message"` 而不是 `'message'` 或 `message` | | ✅ 开发时加错误提示 | 让前端知道怎么改 | --- 现在你只需要运行这行命令就能成功测试: ```powershell curl.exe -X POST http://127.0.0.1:8000/api/chat/ -H "Content-Type: application/json" -d "{\"message\": \"福州鱼丸是怎么做的?\"}" ``` ✅ 就不会报 JSON 解析错误了! ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值