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

请求如下:

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){
Utf8Decoder utf8decoder = Utf8Decoder();
backResult = json.decode(utf8decoder.convert(response.bodyBytes));
}else{
print('数据请求错误:${response.statusCode}');
}
return backResult;
});

  

请求发送之后会出现如下报错

E/flutter ( 7295): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: Bad state: 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){
Utf8Decoder utf8decoder = Utf8Decoder();
backResult = json.decode(utf8decoder.convert(response.bodyBytes));
}else{
print('数据请求错误:${response.statusCode}');
}
return backResult;
});

  

处理之后再提交即可成功

注意:

[body]设置请求的正文。它可以是[String],[List]或[Map]。如果它是一个String,则使用[encoding]进行编码,并将其用作请求的主体。请求的内容类型将默认为“text / plain”。

如果[body]是List,它将用作请求正文的字节列表。

如果[body]是Map,则使用[encoding]将其编码为表单字段。请求的内容类型将设置为"application/x-www-form-urlencoded"; 这不能被覆盖。[encoding]默认为[utf8]。

最新文章

  1. IOS开发之获取Storyboard创建的ViewController
  2. VM arguments
  3. TBB 学习笔记
  4. watir学习系列--Watir API介绍
  5. C/C++程序从编译到链接的过程
  6. fill的用法
  7. JavaIO(04)字符流--Writer and Reader
  8. Android 异常捕获
  9. 快速傅里叶变换(FFT)
  10. MSP430单片机的中断
  11. Linux内核空间-用户空间通信之debugfs
  12. JavaScript高程--<script>标签
  13. 201521123108 《Java程序设计》第13周学习总结
  14. jQuery: Callbacks
  15. 【全网最全的博客美化系列教程】08.自定义地址栏Logo
  16. Android NDK学习(一):目录结构解析
  17. Confluence 6 针对站点维护使用只读模式
  18. python set和get实现
  19. 手把手教你安装mac版hadoop2.7.3教程
  20. 四:DRF项目开发的准备

热门文章

  1. 微信小程序跳到指定页面不生效
  2. mysql中binglog底层原理分析
  3. 介绍两个好玩的和Github相关的Chrome扩展
  4. bootsctrap4 datepicker时间选择插件
  5. Linux下创建NFS来实现共享文件
  6. Ubuntu系统---WeChat安装
  7. libusb_bulk_transfer 异步同步
  8. 数据库 MySQL:Windows 环境安装教程
  9. 用tensorflow实现SVM
  10. 前端css知识实现自动打字,文字滚动