【问题标题】:HTTP send list data to raw body as request in flutterHTTP将列表数据作为flutter中的请求发送到原始正文
【发布时间】:2021-10-21 18:45:37
【问题描述】:

我正在尝试调用具有原始正文请求参数的 POST API。原始正文还包含列表数据。我还附上了邮递员请求和我尝试过的代码。我没有得到成功的回应。如果我做错了什么请纠正我

我的代码:

Future<SaveBookingModel> saveBookingModel(SaveBookingRequestModel saveBookingRequestModel, BuildContext context) async{

  String url = baseUrl + "booking/save";

  var body = {
    "customer_id": "2",
    "location_id": "1",
    "discount_amount": "20.00",
    "discount_voucher": "V123",
    "BookingItems": [{
      "court_id": "3",
      "from_time": "21/10/2021 7:00PM",
      "to_time": "21/10/2021 8:00PM ",
      "amount": "150.00",
      "hours": "1",
      "time_slot_from": "7",
      "time_slot_to": "8"
    },
      {
        "court_id": "3",
        "from_time": "21/10/2021 10:00PM",
        "to_time": "21/10/2021 11:00PM",
        "amount": "100.00",
        "hours": "1",
        "time_slot_from": "10",
        "time_slot_to": "11"
      }
    ],
    "BookingPayments": [{
      "paid_amount": "230.00",
      "payment_desc": "desc",
      "payment_status": "1",
      "payment_method": "8",
      "reference1": "reference1",
      "reference2": "reference2",
      "reference3": "reference3"
    }
    ]
  };
  print("Save booking request body ${saveBookingRequestModel.toJson()}");
  Utils.showLoaderDialog(context);
  final response = await http.post(Uri.parse(url), headers: {
  "Accept": "application/json",
  "Content-Type":"application/json",
    'Authorization':'Bearer ${Utils.token}',
  }, body: body
  );

  print("Save booking request response $saveBookingRequestModel");
  print("Save booking response response ${response.body}");
  if(response.statusCode == 200){
    Navigator.pop(context);

      return SaveBookingModel.fromJson(json.decode(response.body));


  }else {
    return Utils.errorDialog(context, "Something went wrong");
  }

}

【问题讨论】:

  • 一切看起来都不错,可以添加一些日志吗?实际上,怎么可能接收不到错误或警告?
  • 嗨@SalihCan 是的,它显示错误。在某些更改或有时类型转换错误后,它有时会显示错误的请求。我正在尝试许多不同的方式,但每次都失败以显示成功。你能为上面的 json 添加解决方案吗?这对我有很大帮助。

标签: flutter http dart


【解决方案1】:

来自您在上面使用的 post 方法的文档:

如果 [body] 是 Map,则使用 [encoding] 将其编码为表单字段。请求的内容类型将设置为“application/x-www-form-urlencoded”;这不能被覆盖。

但您的内容类型实际上是 application/json。因此,您需要对地图进行 json 编码以使请求成功。导入dart:convert 并将映射传递给jsonEncode 函数。

【讨论】:

  • 我已经将 jsonEncode 添加到 body 仍然没有工作。你可以为上面的json添加例子吗?它真的会帮助我
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-15
  • 2022-01-18
  • 2011-05-26
  • 2020-07-31
  • 2020-02-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多