Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do POST in Dart command line HttpClient

Tags:

dart

I'm struggling with putting together a Dart command line client capable of doing http POST. I know that I can not use dart:html library and have to use dart:io

The beginning seems simple:

HttpClient client = new HttpClient();
client.getUrl(Uri.parse("http://my.host.com:8080/article"));

The question is: what is the correct syntax and sequence to make this HttpClient do a POST and to be able to pass a JSON-encoded string into this post?

like image 584
Eugene Goldberg Avatar asked Jan 31 '14 22:01

Eugene Goldberg


1 Answers

use http package and dart:convert

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

void main() {


  var url = 'http://httpbin.org/post';
  http.post(url, body: JSON.encode({'test': 'value'})).then((response) {
    print("Response status: ${response.statusCode}");
    print("Response body: ${response.body}");
  });
}

For adding custom headers, handling errors etc. see https://www.dartlang.org/dart-by-example/#making-a-post-request

like image 187
tomaszkubacki Avatar answered Oct 21 '22 06:10

tomaszkubacki