Flutter - Send Json over HTTP Post

You'll have to add the content-type to your header, setting its value to application/json.

By specifying Accept you're saying that your client is able to understand that response type, not that your request content is of the JSON type.

Basically you're saying "hey there, I'm able to understand JSON, so you can send it to me and I'll be fine with it" but you're not saying "hey I'm going to send you a JSON, be prepared for it!"

For a better understanding, you can find more about Accept here and Content-type here.


Send Json and Accept Json using:-

    Future<String> addData(Map<String, dynamic> request) async {
    final url = 'http_url';
    try {
      final response = await http.post(url,
          headers: {
        "content-type" : "application/json",
        "accept" : "application/json",
      },
      body: jsonEncode(request));
      final responseData = jsonDecode(response.body) as Map<String,dynamic>;
      return responseData['message'];
    } catch (error) {
      throw error;
    }
  }

You are using incomplete headers for sending the json payload. That is why the server is not accepting you request.

Use the following headers instead:

headers: {
        "content-type" : "application/json",
        "accept" : "application/json",
      },

Tags:

Flutter