Http POST request with json content-type in dart:io

Issue

How to perform HTTP POST using the console dart application (using dart:io or may be package:http library. I do something like that:

import 'package:http/http.dart' as http;
import 'dart:io';

  http.post(
    url,
    headers: {HttpHeaders.CONTENT_TYPE: "application/json"},
    body: {"foo": "bar"})
      .then((response) {
        print("Response status: ${response.statusCode}");
        print("Response body: ${response.body}");
      }).catchError((err) {
        print(err);
      });

but get the following error:

Bad state: Cannot set the body fields of a Request with content-type "application/json".

Solution

From http.dart:

/// [body] sets the body of the request. It can be a [String], a [List<int>] or
/// a [Map<String, String>]. If it's a String, it's encoded using [encoding] and
/// used as the body of the request. The content-type of the request will
/// default to "text/plain".

So generate the JSON body yourself (with JSON.encode from dart:convert).

Answered By – Quentin

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *