Home > Blockchain >  How to post JSON String NOT Object in request body?
How to post JSON String NOT Object in request body?

Time:08-05

The body is String similar to this. I tried many different ways as below, but none worked.

await http.post(
  Uri.parse(url),
  headers: {
    "content-type": "application/json",
  },
  body: "3ea9554d-7a1f-4f20-f6f5-08da74d069a8",      // "'a' is invalid within a number, immediately after a sign character
  // body: "\"3ea9554d-7a1f-4f20-f6f5-08da74d069a8\"",  // The JSON value could not be converted to
  // body: jsonEncode("3ea9554d-7a1f-4f20-f6f5-08da74d069a8"), // The JSON value could not be converted to
  // body: jsonEncode("\"3ea9554d-7a1f-4f20-f6f5-08da74d069a8\""), // The JSON value could not be converted to
  // body: jsonEncode(jsonDecode('3ea9554d-7a1f-4f20-f6f5-08da74d069a8')),  // FormatException: Missing expected digit (at character 3)
  // body: jsonEncode(jsonDecode("\"3ea9554d-7a1f-4f20-f6f5-08da74d069a8\"")),  // The JSON value could not be converted to
);

CodePudding user response:

Since you set the content-type to application/json, you can't pass a string, only an object, like:

body: jsonEncode({"value": "3ea9554d-7a1f-4f20-f6f5-08da74d069a8"})

To pass your string as you'd like, set the content type like this:

"content-type": "text/plain"

But according to the documentation you can try to remove the headers part completely, since it seems that it will be text/plain automatically if you pass a string as body.

CodePudding user response:

Thanks to the answer given by Wali Khan. The solution is

final request = http.Request('POST', Uri.parse(url));
request.headers.addAll({
  "content-type": "application/json",
});
request.body = json.encode("3ea9554d-7a1f-4f20-f6f5-08da74d069a8");
http.StreamedResponse response = await request.send();
  • Related