将邮递员呼叫转换为Dart / Flutter API呼叫

时间:2019-11-07 11:01:12

标签: rest http flutter dart postman

我希望使用Nutritionix api来为我的应用程序的用户获取食物信息,我设法在Postman中工作,但是我无法将其转换为dart代码。我收到此错误:“ {消息:位置0的JSON中的意外令牌“}”

这是我的(POST)邮递员电话:

Headers for POST call Body for POST call

这是我将其转换为飞镖代码的尝试:

  Future<void> fetchNutritionix() async {
    String url = 'https://trackapi.nutritionix.com/v2/natural/nutrients';
    Map<String, String> headers = {
      "Content-Type": "application/json",
      "x-app-id": "5bf----",
      "x-app-key": "c3c528f3a0c68-------------",
      "x-remote-user-id": "0",
    };
    String query = 'query: chicken noodle soup';

    http.Response response =
        await http.post(url, headers: headers, body: query);

    int statusCode = response.statusCode;
    print('This is the statuscode: $statusCode');
    final responseJson = json.decode(response.body);
    print(responseJson);

    //print('This is the API response: $responseJson');
  }

任何帮助将不胜感激!而且,再次感谢您!

4 个答案:

答案 0 :(得分:3)

您的邮递员屏幕截图显示x-www-form-urlencodedcontent-type,那么为什么要在标题中将其更改为application/json?删除内容类型标头(程序包将为您添加内容标头),只需将映射传递给body参数:

  var response = await http.post(
    url,
    headers: headers,
    body: {
      'query': 'chicken soup',
      'brand': 'acme',
    },
  );

答案 1 :(得分:0)

查看您要发布的查询

您的邮递员输入是x-www-form-urlencoded,而不是纯文本

String query = 'query: chicken noodle soup';

为什么不更好地尝试JSON

String query = '{ "query" : "chicken noodle soup" }';

答案 2 :(得分:0)

现在,您还可以通过单击Code按钮下方的Save按钮来为邮递员请求生成Dart代码(以及其他多种语言)。

答案 3 :(得分:0)

enter image description here

单击请求选项卡中的三个点按钮并选择代码选项,然后选择要将代码转换为的语言