【问题标题】:How to use http.post and send as String Json Object in Flutter如何在 Flutter 中使用 http.post 并作为 String Json 对象发送
【发布时间】:2019-10-02 00:05:56
【问题描述】:

我正在尝试将 json 对象发送到 api 端点。但我得到以下信息:

I / flutter(28184): 200
I / flutter(28184): {"error": "the JSON object must be str, not 'bytes'"}

我尝试了以下方法:

Future<http.Response> sendPost() async{
    var post = {
      "profile_id" : "${_profile_id}",
      "profile_name" : "${_profile_Name}",
      "profile_country" : "${_profile_country}",
      "post_id" : "${current_post_id}",
      "post_image_id" : "${current_post_image}",
      "post_desc" : "La La La La La La",
      "post_likes" : "${post_likes}",
      "post_timestamp" : "05-06-2019 22:34",
      "post_comments" : [],
      "post_comments_profile_name" : [],
      "post_comments_profile_image_id" : [],
      "post_comments_timestamp" : []
    };


    var body = utf8.encode(json.encode(post));

    var addPost = await http.post(
      url,
      headers: {"content-type" : "application/json"},
      body: body

      );

      print("${addPost.statusCode}");
      print("${addPost.body}");
      return addPost;
  }

另外,当您回答时,请记住此 Map 中应该有空数组。

【问题讨论】:

    标签: json http post dart flutter


    【解决方案1】:

    不要使用 utf8.encode() 转换地图。 因为 JSON 对象必须是字符串而不是字节。 直接发图:

    var addPost = await http.post(
        url,
        body: post
    );
    

    我从评论中了解到您希望将来检索字符串数组。 不用担心可以轻松实现:

    链接:Flutter how to convert String to List<String>

    【讨论】:

      【解决方案2】:

      为了将 JSON 发送到正文中,您应该将 JSON 串起来。

      var body = JSON.stringify(post);

      我认为不需要编码。

      【讨论】:

        【解决方案3】:

        无需转换地图:

        var body = utf8.encode(json.encode(post)); // delete this
        

        只需像这样将地图发送到正文:

        var addPost = await http.post(
            url,
            body: post
        );
        

        【讨论】:

        • 您好,感谢您的回复,由于我的地图包含字符串数组,我不能这样使用。我该如何克服这个问题?
        猜你喜欢
        • 1970-01-01
        • 2013-02-09
        • 1970-01-01
        • 1970-01-01
        • 2018-06-27
        • 1970-01-01
        • 2016-12-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多