【问题标题】:Fetch API with http flutter使用 http Flutter 获取 API
【发布时间】:2021-11-20 15:45:08
【问题描述】:

我正在尝试使用 http 包获取 api。它正在使用邮递员。它在正文中有表单数据。我无法弄清楚我们如何在标题中调用表单数据。我会附上邮递员的图片以便更好地理解。

我的代码:

Future<LocationDetailsById> locationDetailsByID(BuildContext context,String locationID) async{
      String url = baseUrl + "location/detailsbyid";
      var body = {

        "location_id":int.parse(locationID)};
      Utils.showLoaderDialog(context);
      final response = await http.post(Uri.parse(url), headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/form-data',
        'Authorization':'Bearer ${Utils.token}',
      }, body: jsonEncode(body)
      );
      print("request $locationID");
      print("response ${response.body}");
      if(response.statusCode == 200){
        Navigator.pop(context);

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


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

    }

【问题讨论】:

    标签: flutter http


    【解决方案1】:

    我怀疑您的表单帖子的正文格式不正确,它看起来像是针对接受 JSON 正文的端点的格式。

    我会将帖子正文格式化为FormData,如下所示:

    String url = baseUrl + "location/detailsbyid";
    FormData formData = FormData.fromMap(body);
    await http.post(url: url, body: formData, headers: {...});
    

    【讨论】:

      猜你喜欢
      • 2021-10-25
      • 1970-01-01
      • 2019-11-07
      • 2021-02-15
      • 1970-01-01
      • 2021-01-14
      • 1970-01-01
      • 2019-07-05
      • 1970-01-01
      相关资源
      最近更新 更多