具有Map< String,dynamic>的Dart HTTP POST;作为身体 [英] Dart HTTP POST with Map<String, dynamic> as body

查看:666
本文介绍了具有Map< String,dynamic>的Dart HTTP POST;作为身体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Dart http程序包post方法仅接受StringList<int>Map<String, String>作为请求 body . 我需要使用Content-Type标头application/json将此类的对象发送为主体:

The Dart http package's post method only accepts a String, a List<int> or a Map<String, String> as the request body. I need to send and object of this class as body with Content-Type header application/json:

class CreateListingRequest {
  String title;
  List<ListingImage> images;
  List<int> categoryIds;
}

其中ListingImage

class ListingImage {
  String url;
  int position;
}

在邮递员中,我将使用Content-Type标头application/json将正文构建为原始json,

In Postman I would build the body as raw json with Content-Type header application/json like this:

{
  "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]
}

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

It seems to me that if I could send a Map<String, dynamic> that would solve the problem but I can only send Map<String, String>.

请帮助.

推荐答案

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

Use String encoded = json.encode(theMap); then post encoded. If you need a particular character encoding (e.g. utf-8) then further encode the string using utf8.encode(encoded) and post the resulting byte array. (The second step should be unnecessary for utf-8 as I think that is the default.)

值得考虑这三种变体的作用:

It's worth considering what the 3 variants do:

  • List<int>-发送不透明的字节数组
  • String编码 使用字符编码将字符串转换成字节-并发送字节 数组
  • Map<String, String>-在x-www-form-urlencoded中对字符串键/值对进行编码并将其发送.
  • List<int> - sends an opaque byte array
  • String encodes the string into bytes using a character encoding - and sends the byte array
  • Map<String, String> - encodes the string key/value pairs in x-www-form-urlencoded and sends that.

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

If you want to send more complex data then you need to convert it into one of the above (and the server needs to know how to decode it). That's where the content-type header is useful. Ultimately, the server receives a byte array and converts it back into, for example, a string, or some json, or a set of form fields, or an image. It knows how to do this based on the header and any specified encoding.

这篇关于具有Map&lt; String,dynamic&gt;的Dart HTTP POST;作为身体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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