如何在Flutter中通过API发送数据?

问题描述 投票:0回答:2

[当我尝试通过API登录(电子邮件和密码参数)时,数据以行格式传递,但是我想以表单格式发布数据。由于这个问题,当我传递数据时,它不接受参数值,并显示null并给出错误。那么,我该如何解决这个问题呢?

api flutter dart http-post postman
2个回答
0
投票

只需添加带有json_data的标头。

Future<login> requestLogin(String username, String password , String device_id) async {
      Map<String, String> headers = {"Content-type": "application/x-www-form-urlencoded"};
      var json_body = { 'email' : username , 'password': password ,'device_id': device_id};

      if(token != null){
        headers.addAll({"Authorization" : "Bearer "+token});
      }
      //  make POST request
      final response = await http.post(baseUrl+ "/login", headers: headers, body: json_body);
      print(response.body);
      if (response.statusCode == 200) {
        // If server returns an OK response, parse the JSON.
        // return Post.fromJson(json.decode(response.body));
        print(response.body);
        return login.fromJson(json.decode(response.body));
      } else {
        // If that response was not OK, throw an error.
        throw Exception(response.body);
      }
    }

0
投票

对于您的发帖请求,只需像这样传递您的参数

您的发帖请求应如下所示。

response = await http.post("your_api_url",
                           body:{"email" : "value",
                                 "password" : "value"});
© www.soinside.com 2019 - 2024. All rights reserved.