我正在try 使用url编码的内容类型在fltter中发出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-urlencode发送,则需要对其进行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版本的(当然,您也可以在FIFTER中使用它) 如果你想坚持使用package:http版本,那么你需要稍微调整一下你的 map .body号一定是Map<String, String>号.你需要决定你想要什么作为你的POST参数.你想要两个吗:HomeTeam和AwayTeam?或者一个,比方说,team Json?

此代码

  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&; colored颜色 =蓝色和蓝色;主队=%7B%22team%22%3A%22team+A%22%7D&;awayTeam=%7B%22团队%22%3A%22团队+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标头中发送长度.您仍然必须进行json编码.

Flutter相关问答推荐

Flutter -如何从布局填充(对称水平)中排除小部件?

在Riverpod ConsumerWidget中使用文本编辑控制器

如何创建一个按钮来在Ffltter Webview中转到上一页?

blocTest错误:没有从`when()`中调用方法存根

应为Map String,dynamic类型的值,但得到的值为type()= Map String,dynamic'

在创建显示此错误的Flutter 深度链接时

使用 forLoops 在 Dart 中进行单元测试会返回 stackoverflow

如何在 Flutter 中以背景 colored颜色 制作圆圈的一部分

在 flutter 的列中使用 Expanded 时出现渲染 Flex 错误

如何从flutter连接PostgreSQL数据库?

更新番茄计时器值不会触发 Flutter Riverpod 中的alert 声音

Flutter url_launcher 插件抛出java.lang.IllegalArgumentException:接收器未注册:io.flutter.plugins.urllauncher.WebViewActivity

如何更改 DropDownMenu 的显示方向?

如何删除图像边框半径与其父容器边框半径之间的空白

Agora VideoCall 不显示远程视频网格

flutter - 无法解析 JSON 消息:文档为空

如何在 Flutter 中将列小部件添加到行小部件?

Flutter RawMaterialButton 常量相对大小

使用 hydrad_bloc 的预览包

Flutter 评级栏包选中和未选中的容器