flutter - Http请求发送了一个空的body
问题描述
这是我的帖子请求的代码:
Future<User> createUser(String name,String username,String email,String password, String passwordConfirm, String role) async {
final response = await http.post('http.register.com',
body:jsonEncode(<String, String>{
'name': name,
'username': username,
'number': email,
'password': password,
'passwordConfirm':passwordConfirm,
'role':role,
})
);
if (response.statusCode == 200) {
return User.fromJson(json.decode(response.body));
} else {
throw Exception('Failed to load request');
}
}
问题是,一旦我发送它,API 的正文就变成空的了。我该如何解决?
_futureUser = createUser(_namecontroller.text ,_usernamecontroller.text,_email.text ,_passwordcontroller.text ,_passwordConfirmcontroller.text, _role);
我放了更多代码,我认为这可能会有所帮助。
解决方案
根据post
功能文档https://pub.dev/documentation/http/latest/http/post.html
如果body
是String
,content-type
则请求的默认为"text/plain"
.
如果body
是Map
,content-type
则请求的 将默认为"application/x-www-form-urlencoded"
。
您可以将标题设置为application/json
代码片段
http.post(url,
headers: {"Content-Type": "application/json"},
body: body
推荐阅读
- c++ - 将函数指针传递给另一个类的方法
- html - 无法使用 Find_All 刮取班级信息
- html - 什么是(没有孩子)用于?
- javascript - 在节点中,我有一个名为“错误”的 json 对象
- python - Django - 图像未在第二个应用程序中加载
- javascript - JS如何获取推特的名字
- .net - 无法使用 .Net EF(2.2) 核心存储库模式访问 oracle 存储过程
- python - Spyder 自动前进到下一行
- c# - IE Webdriver Click() 单击元素但没有任何反应
- python - 使用 pytest-cov 和 subprocess.Popen 进行覆盖测试