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
I'd like to recommend dio package to you , dio is a powerful Http client for Dart/Flutter, which supports Interceptors, FormData, Request Cancellation, File Downloading, Timeout etc.
dio is very easy to use:
Performing a Get request:
response=await dio.get(url)
Performing a POST request:
response=await dio.post(url,data:{"id":12,"name":"wendu"})
Sending FormData:
FormData formData = new FormData.from({
"name": "wendux",
"file1": new UploadFileInfo(new File("./upload.pdf"), "upload1.pdf")
});
response = await dio.post("/info", data: formData)
Downloading a file:
response=await dio.download("https://www.google.com/","./xx.html")
More details please refer to dio in Github: https://github.com/flutterchina/dio.
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