How to do POST in Dart command line HttpClient

2020-03-20 13:08发布

问题:

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?

回答1:

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



回答2:

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.



标签: dart