I need to create a post request with a JSON that contains an Array. The http.post method only accepts Map<String, String>. Because of this, I cannot pass a Map with type <String,dynamic> since the Map will contain a List. Here's my code for an explicit HttpClientRequest:
String jsonString = json.encode(body); // encode map to json
List<int> bodyBytes = utf8.encode(jsonString); // utf8 encode
HttpClient client = new HttpClient();
HttpClientRequest request = await client.postUrl(uri);
// it's polite to send the body length to the server
request.headers.set('Content-Length', bodyBytes.length.toString());
request.headers.set('Authorization', '...');
request.headers.set('X-Authorization', apiKey);
request.headers.set("Accept", "application/json");
request.headers.set('Content-Type', 'form-data');
request.add(bodyBytes);
HttpClientResponse response = await request.close();
response.transform(utf8.decoder).listen((contents) {
// handle data
return jsonDecode(contents);
});
The problem is, the above request fails.
EDIT:
The json that is created is:
{
"subject":"PLEASE",
"message":"JUST. WORK.",
"filter":"[8]",
}
But the JSON the server expects is:
{
"subject":"PLEASE",
"message":"JUST. WORK.",
"filter":[8],
}
My main concern is how does one create a JSON array...
Map<String, dynamic>?bodytojsonString, and that's what you're passing to the http client, which sounds right. I don't understand what you mean by "post accepts body of type Map<String, String>"; I don't see where you're passing this map, the post/postUrl methods don't take a map.