使用 Map<String, dynamic> 作为主体的 Dart HTTP POST

Tou*_*der 3 json dart flutter

Dart http 包post方法只接受 a String、aList<int>或 aMap<String, String>作为请求正文。我需要将此类的对象作为带有 Content-Type 标头应用程序/json 的主体发送:

class CreateListingRequest {
  String title;
  List<ListingImage> images;
  List<int> categoryIds;
}
Run Code Online (Sandbox Code Playgroud)

这里ListingImage

class ListingImage {
  String url;
  int position;
}
Run Code Online (Sandbox Code Playgroud)

在 Postman 中,我会将正文构建为带有 Content-Type 标头的原始 json,application/json如下所示:

{
  "title": "Testing transaction force fail",
  "listing_images": [
    {
      "url": "https://picsum.photos/500/500/?image=336",
      "position": 0
    },
    {
      "url": "https://picsum.photos/500/500/?image=68",
      "position": 1
    },
    {
      "url": "https://picsum.photos/500/500/?image=175",
      "position": 2
    }
  ],
  "category_ids": [19, 26]
}
Run Code Online (Sandbox Code Playgroud)

在我看来,如果我可以发送一个Map<String, dynamic>可以解决问题的文件,但我只能发送Map<String, String>.

请帮忙。

Ric*_*eap 10

使用String encoded = json.encode(theMap);然后发布encoded。如果您需要特定的字符编码(例如 utf-8),则使用utf8.encode(encoded)并发布生成的字节数组进一步对字符串进行编码。(第二步对于 utf-8 应该是不必要的,因为我认为这是默认设置。)

值得考虑这 3 个变体的作用:

  • List<int> - 发送一个不透明的字节数组
  • String 使用字符编码将字符串编码为字节 - 并发送字节数组
  • Map<String, String>- 将字符串键/值对编码x-www-form-urlencoded并发送。

如果要发送更复杂的数据,则需要将其转换为上述数据之一(并且服务器需要知道如何对其进行解码)。这就是content-type标题有用的地方。最终,服务器接收一个字节数组并将其转换回,例如,字符串、某些 json、一组表单字段或图像。它知道如何根据标头和任何指定的编码来做到这一点。


Val*_*ova 8

我在搜索如何发送 POST 请求时发现了这个问题,经过List<Map<String, dynamic>> 一番思考,我编写了代码来执行此操作。它也适用于最初的问题(您只需将函数的参数设置为Map<String, dynamic>类型)。

import 'package:http/http.dart' as http;
import 'dart:convert';

//...

static const Map<String, String> _JSON_HEADERS = {
    "content-type": "application/json"
  };

void sendPost(List<Map<String, dynamic>> data) {
  http.Client client = new http.Client();
  final String encodedData = json.encode(data);
  client.post(ADDRESS, //your address here
              body: encodedData, headers: _JSON_HEADERS);
}
Run Code Online (Sandbox Code Playgroud)