dart - 如何在 flutter 中使用 url 编码的主体发出 HTTP POST 请求?

我正在尝试在内容类型为 url 编码的情况下发出一个 post 请求。当我写 body : json.encode(data) ,它编码为纯文本。

如果我写 body: data我收到错误 type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String' in type cast

这是数据对象

var match = {
  "homeTeam": {"team": "Team A"},
  "awayTeam": {"team": "Team B"}
};

还有我的要求

var response = await post(Uri.parse(url),
    headers: {
      "Accept": "application/json",
      "Content-Type": "application/x-www-form-urlencoded"
    },
    body: match,
    encoding: Encoding.getByName("utf-8"));

最佳答案

您需要添加三个额外的步骤: 首先,您需要将 JSON 映射转换为字符串(使用 json.encode) 然后,如果您想将其作为 application/x-www-form-urlencoded 发送,则需要对其进行 Uri 编码。 最后,您需要为要发布的参数命名。

例如(注意,这里使用的是dart:io HttpClient,但基本一样):

  Future<HttpClientResponse> foo() async {
    Map<String, dynamic> jsonMap = {
      'homeTeam': {'team': 'Team A'},
      'awayTeam': {'team': 'Team B'},
    };
    String jsonString = json.encode(jsonMap); // encode map to json
    String paramName = 'param'; // give the post param a name
    String formBody = paramName + '=' + Uri.encodeQueryComponent(jsonString);
    List<int> bodyBytes = utf8.encode(formBody); // utf8 encode
    HttpClientRequest request =
        await _httpClient.post(_host, _port, '/a/b/c');
    // it's polite to send the body length to the server
    request.headers.set('Content-Length', bodyBytes.length.toString());
    // todo add other headers here
    request.add(bodyBytes);
    return await request.close();
  }

以上为dart:io版本(当然,你可以在 Flutter 中使用) 如果您想坚持使用 package:http版本,那么您需要稍微调整一下您的 map 。 body必须是 Map<String, String> .你需要决定你想要什么作为你的 POST 参数。你想要两个:主队和客队?或者一个,比如说,teamJson?

这段代码

  Map<String, String> body = {
    'name': 'doodle',
    'color': 'blue',
    'homeTeam': json.encode(
      {'team': 'Team A'},
    ),
    'awayTeam': json.encode(
      {'team': 'Team B'},
    ),
  };

  Response r = await post(
    url,
    body: body,
  );

在电线上产生这个

name=doodle&color=blue&homeTeam=%7B%22team%22%3A%22Team+A%22%7D&awayTeam=%7B%22team%22%3A%22Team+B%22%7D

或者,这个

  Map<String, String> body = {
    'name': 'doodle',
    'color': 'blue',
    'teamJson': json.encode({
      'homeTeam': {'team': 'Team A'},
      'awayTeam': {'team': 'Team B'},
    }),
  };

  Response r = await post(
    url,
    body: body,
  );

在电线上产生这个

name=doodle&color=blue&teamJson=%7B%22homeTeam%22%3A%7B%22team%22%3A%22Team+A%22%7D%2C%22awayTeam%22%3A%7B%22team%22%3A%22Team+B%22%7D%7D

package:http客户端负责:对 Uri.encodeQueryComponent 进行编码,utf8 编码(注意这是默认值,因此无需指定)并在 Content-Length header 中发送长度。您仍然必须进行 json 编码。

https://stackoverflow.com/questions/49797558/

相关文章:

dart - 如何清除 Flutter 的图片缓存?

dart - 如何在 Flutter 中更改键盘上的文本输入操作按钮(返回/回车键)?

dart - Android Studio 3.0.1 上未显示新的 Flutter 项目向导

android - 如何构建符合 Google Play 64 位要求的应用程序?

android - Flutter 中的字符串 xml 文件

flutter - 如何在 flutter 中为文本添加阴影?

flutter - 如何修复 HttpException : Connection closed b

java - Flutter 应用程序体积太大

ios - 使用 Flutter 在 Windows 环境下开发 iOS 设备

dart - 如何检查当前路线是哪条?