【问题标题】:How to send data through API in Flutter?Flutter中如何通过API发送数据?
【发布时间】:2020-06-16 13:13:10
【问题描述】:

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

> This _loginUser() method In call on login button click.


_loginUser(context) async {
    Map<String, dynamic> loginBodyResponse = {
      "email": _emailController.text,
      "password": _passswordController.text,
    };
    try {
      setState(() {
        _isLoading = true;
      });
> APIs call
      Map loginResponse = await NetworkHttp.postHttpMethod(
          '${AppConstants.apiEndPoint}${AppConstants.loginApi}',
          loginBodyResponse);

          print('email:' + _emailController.text);
          print('Password:' + _passswordController.text);
          print(loginBodyResponse);

      print('===================Login Response=========================');
      print(loginResponse['body']);

      print(loginResponse['body']['login']);

      print("---------------------------");
      if (loginResponse['body']['status'] != "success") {
        setState(() {
          _isLoading = false;
        });
        String errormessage = loginResponse['body']['msg'];
        print("---------------------------");
        print(errormessage);

        ErrorDialog.showErrorDialog(context, errormessage, "Error");
      } else {
        print("Login Successfully");
        print("============================================");
        setState(() {
          _isLoading = false;
        });
        NavigatorHelper.verifyOtpScreen(context);
      }
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      ErrorDialog.showErrorDialog(context, e.toString(), "Error");
      print('error while login $e');
    }
  }

我在上面提到的代码中使用的 NetworkHttp 类。当我尝试登录时,它在控制台中显示空参数

class NetworkHttp {
  static Future<Map<String, String>> _getHeaders() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    final String token = prefs.getString('token');
    if (token != null) {
      return {
        'Content-type': 'application/json',
        'Accept': 'application/json',
        'AccessToken': '$token',
      };
    } else {
      return {
        'Content-type': 'application/json',
        'Accept': 'aapilcation/json',
      };
    }
  }

static Future<Map<String, dynamic>> postHttpMethod(String url, body) async {
    print('url');
    print(url);
    print('body');
    print(body);
    Map headers = await _getHeaders();
    print('headers');
    print(headers);
    http.Response response = await http.post(
      url,
      headers: headers,
      body: json.encode(body),
    );
    Map<String, dynamic> responseJson = {
      'body': json.decode(response.body),
      'headers': response.headers
    };
    return responseJson;
  }

【问题讨论】:

  • 请分享您正在使用的代码和您遇到的错误,以便可以帮助您解决您收到的错误

标签: api flutter dart http-post postman


【解决方案1】:

通过您的发布请求,只需像这样传递您的参数

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

response = await http.post("your_api_url",
                           body:{"email" : "value",
                                 "password" : "value"});

【讨论】:

    【解决方案2】:

    只需添加带有 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);
          }
        }
    

    【讨论】:

      猜你喜欢
      • 2016-04-05
      • 2021-06-04
      • 2018-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-16
      相关资源
      最近更新 更多