【问题标题】:Http request sent an empty bodyHttp请求发送了一个空的body
【发布时间】:2020-03-24 22:01:54
【问题描述】:

这是我发帖请求的代码:

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);

我添加了一些代码,我认为这可能会有所帮助。

【问题讨论】:

    标签: flutter dart http-post


    【解决方案1】:

    根据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

    代码sn-p

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-26
      • 2022-09-23
      • 2022-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-16
      相关资源
      最近更新 更多