flutter - Http请求发送了一个空的正文

标签 flutter dart http-post

这是我的帖子请求的代码:

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
如果bodyString,则请求的content-type将默认为"text/plain"
如果bodyMap,则请求的content-type将默认为"application/x-www-form-urlencoded"
您可以将 header 设置为application/json
程式码片段

http.post(url,
      headers: {"Content-Type": "application/json"},
      body: body

关于flutter - Http请求发送了一个空的正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60840008/

相关文章:

dart - 调试Dart Web-UI应用程序时断点不起作用

javascript - 通过 AngularJS 发送带有多个数据的 HTTP Post

perl - 为什么 curl POST 请求会使我的 Catalyst::Controller::REST Controller 崩溃?

flutter - 找不到捆绑的 Java 版本?

flutter - 使用可注入(inject) pub 包时未定义函数 '$initGetIt'

flutter - Flutter实例成员 ‘{0}’无法使用静态访问权限访问

flutter - 要在单击按钮时显示AlertDialog,在“按下的方法”上显示错误。 (未定义名称 'context'。)

json - 解析 Flutter 中的对象列表错误

animation - 如何在 appBar 图标的购物车图标上添加商品编号?我怎样才能让它动画添加新项目?

java - 无法在 Java HTTP POST 请求中发送 JSON