Search code examples
flutterdartdart-pubdart-http

Flutter: Http post request Error Invalid media type: expected


I am making an http post request using http dependency. I am facing the below error in my response. I am posting my code below:

flutter: Error on line 1, column 32: Invalid media type: expected /[^()<>@,;:"\\\/[\]?={} \t\x00-\x1F\x7F]+/.
      ╷
    1 │ application/json;charset=utf-8;
      │

                            ^

below is the code in which i am facing the error:

try {
    String url = 'https://app.restroapp.com/';
    Map<String, String> headers = {"Content-type": "application/json"};
    String json = '{"device_id": "abaf785580c22722", "user_id": "", "device_token": "","platform":"android"}';

    // make POST request
    Response response = await post(Uri.encodeFull(url), headers: headers, body: json);
    // check the status code for the result
    int statusCode = response.statusCode;
    // this API passes back the id of the new item added to the body
    String body = response.body;

    print(statusCode);
    print(body);

  } catch (e) {
    print(e);
  }

it is wroking in postman, please see the below image: enter image description here


Solution

  • Use this for post request

     Future<Map<String, dynamic>> postRequest(String url, Map jsonMap) async{
         print('$url , $jsonMap');
         HttpClient httpClient = new HttpClient();
         HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
         request.headers.set('content-type', 'application/json');
         request.add(utf8.encode(json.encode(jsonMap)));
         HttpClientResponse response = await request.close();
         String reply = await response.transform(utf8.decoder).join();
         print(reply);
         httpClient.close();
         Map<String, dynamic>map = json.decode(reply);
         return map;
    }