如何在颤动中发出带有url编码主体的HTTP POST请求? [英] How to make HTTP POST request with url encoded body in flutter?

查看:72
本文介绍了如何在颤动中发出带有url编码主体的HTTP POST请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以内容类型为url编码的形式发出发帖请求。当我写 body:json.encode(data)时,它会编码为纯文本。

I'm trying to make an post request in flutter with content type as url encoded. When I write body : json.encode(data), it encodes to plain text.

如果我写 body:data 我会收到错误 type'_InternalLinkedHashMap< String, dynamic>'不是类型转换类型'String'的子类型

If I write body: data I get the error 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编码。
最后,您需要提供要发布名称的参数。

You need to add three additional steps: First, you need to convert the JSON map to a String (using json.encode) Then you need to Uri encode it if you want to send it as application/x-www-form-urlencoded. Lastly, you need to give the parameter that you are posting a name.

例如(请注意,这是使用dart:io HttpClient,但基本相同) :

For example (note, this is using the dart:io HttpClient, but it's basically the same):

  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< String,String>。您需要确定所需的POST参数。您是否想要两个:homeTeam和awayTeam?还是一个,例如teamJson?

The above is for the dart:io version (which, of course, you can use in Flutter) If you would like to stick with the package:http version, then you need to tweak your Map a bit. body must be a Map<String, String>. You need to decide what you want as your POST parameters. Do you want two: homeTeam and awayTeam? or one, say, 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

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

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编码。

the package:http client takes care of: encoding the Uri.encodeQueryComponent, utf8 encoding (note that that's the default, so no need to specify it) and sending the length in the Content-Length header. You must still do the json encoding.

这篇关于如何在颤动中发出带有url编码主体的HTTP POST请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆