小编典典

如何在URL中使用URL编码的主体发出HTTP POST请求?

flutter

我正在尝试用内容编码为url编码的形式发出发帖请求。当我写时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"));

阅读 411

收藏
2020-08-13

共1个答案

小编典典

您需要添加三个附加步骤:首先,您需要将json映射转换为String(使用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进行一些调整。正文必须是Map
。您需要确定所需的POST参数。您是否想要两个:homeTeam和awayTeam?还是一个,例如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,
  );

在电线上产生这个

名称= 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,
  );

在电线上产生这个

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

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

2020-08-13