如何在Flutter中以多部分请求发送Map Object

时间:2019-05-28 21:53:55

标签: flutter dart multipart

在这里,我正在尝试通过多部分请求发送对象映射,但是我的请求将以字符串形式发送,而不是JSON格式,请建议我进行正确的请求。预先感谢。

我尝试了多部分请求,但我的请求应采用正确的形式。

var getApiUrl = 'http://malik-env-test.ap-south-1.elasticbeanstalk.com/webapi/post/create';

  Map userData = {

    "creator": {
      "creatorId": "298",
      "createDate": "2018-12-21 20:44:45.8"
    },
    "info": "$campusInfo",
    "title": "$eventName",
    "postCampusId": "5642"

  };

Uri uri = Uri.parse(getApiUrl);
   http.MultipartRequest request = new http.MultipartRequest('POST', uri);
   request.fields['creator'] = userData['creator'];
   request.fields['info'] = '$campusInfo';
   request.fields['title'] = '$eventName';
   request.fields['postCampusId'] = '5642';
   request.files.add(await http.MultipartFile.fromPath('image_file1', imagePath, contentType: new MediaType('application', 'x-tar')));
//   var body = json.encode(request);
   print(request);
   http.StreamedResponse response = await request.send();
   String jsonData = response.toString();
   print(jsonData);ddd

3 个答案:

答案 0 :(得分:1)

   var userData = json.encode({
     "creator": {
           "creatorId": "298",
            "createDate": "2018-12-21 20:44:45.8"
       },
      "info": "$campusInfo",
      "title": "$eventName",
      "postCampusId": "5642"
    });
    var client = http.Client();
    client
        .post('https://'+ url ,
            headers: {
              'content-type': 'application/json',
            },
            body: body)

答案 1 :(得分:1)

我认为,添加对象字段的最简单方法是使用这样的括号;

request.fields['creator[creatorId]'] = '$creatorId';
request.fields['creator[createDate]'] = '$createDate';
request.fields['title'] = '$eventName';
request.fields['postCampusId'] = '5642';

因此,对于另一个内部的字段,您需要先将对象名称添加到方括号内的字段名称中。

这应该可以正常工作。

答案 2 :(得分:0)

尝试:

request.fields['userData'] = json.encode(userData);

您需要从API规范或服务器所有者中找出用于json的字段名称。我假设使用userData

如果要控制媒体类型,编码等,请将其添加为如下文件:

  request.files.add(
    http.MultipartFile.fromBytes(
      'the_form_field name',
      utf8.encode(json.encode(userData)),
      contentType: MediaType(
        'application',
        'json',
        {'charset': 'utf-8'},
      ),
    ),
  );