Hasan El-Hefnawy
Hasan El-Hefnawy

Reputation: 1569

How to post JSON String NOT Object in request body?

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
);

Upvotes: 0

Views: 1650

Answers (3)

Hasan El-Hefnawy
Hasan El-Hefnawy

Reputation: 1569

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();

Upvotes: 1

Wali Khan
Wali Khan

Reputation: 652

Use postman to autogenerate code like this enter image description here

Upvotes: 1

Peter Koltai
Peter Koltai

Reputation: 9734

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.

Upvotes: 0

Related Questions