在这里,我尝试在多部分请求中发送对象映射,但我的请求是字符串,而不是 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
尝试:
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'},
),
),
);
我认为,添加对象字段的最简单方法是使用这样的括号;
request.fields['creator[creatorId]'] = '$creatorId';
request.fields['creator[createDate]'] = '$createDate';
request.fields['title'] = '$eventName';
request.fields['postCampusId'] = '5642';
因此,对于另一个字段中的字段,您需要将对象名称放在第一位,然后添加到括号内的字段名称中。
这应该可以正常工作。
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: userData )