Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dart

dart-io

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".
like image 688
Roman Avatar asked Dec 19 '14 22:12

Roman


People also ask

How do you send JSON data in Dart?

Use the dart: convert package to convert the response body into a JSON Map. Use the fromJSON() factory method to convert JSON Map into Album if the server returns an OK response with a status code of 200. Throw an exception if the server doesn't return an OK response with a status code of 200.


2 Answers

This is a complete example. You have to use json.encode(...) to convert the body of your request to JSON.

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


var url = "https://someurl/here";
var body = json.encode({"foo": "bar"});

Map<String,String> headers = {
  'Content-type' : 'application/json', 
  'Accept': 'application/json',
};

final response =
    http.post(url, body: body, headers: headers);
final responseJson = json.decode(response.body);
print(responseJson);

Generally it is advisable to use a Future for your requests so you can try something like

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

Future<http.Response> requestMethod() async {
    var url = "https://someurl/here";
    var body = json.encode({"foo": "bar"});

    Map<String,String> headers = {
      'Content-type' : 'application/json', 
      'Accept': 'application/json',
    };

    final response =
        await http.post(url, body: body, headers: headers);
    final responseJson = json.decode(response.body);
    print(responseJson);
    return response;
}

The only difference in syntax being the async and await keywords.

like image 57
draysams Avatar answered Oct 28 '22 14:10

draysams


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

like image 38
Quentin Avatar answered Oct 28 '22 16:10

Quentin