如何在Dart命令行HttpClient中进行POST

时间:2014-01-31 22:52:54

标签: dart

我正在努力组建一个能够执行http POST的Dart命令行客户端。 我知道我不能使用dart:html库并且必须使用dart:io

开头似乎很简单:

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

问题是:使HttpClient执行POST并且能够将JSON编码的字符串传递到此帖子中的正确语法和顺序是什么?

2 个答案:

答案 0 :(得分:9)

使用http包和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}");
  });
}

要添加自定义标题,处理错误等,请参阅https://www.dartlang.org/dart-by-example/#making-a-post-request

答案 1 :(得分:6)

我想向您推荐dio包,dio是Dart / Flutter的强大Http客户端,它支持拦截器,FormData,请求取消,文件下载,超时等。

dio非常易于使用:

执行获取请求:

response=await dio.get(url)

执行POST请求:

response=await dio.post(url,data:{"id":12,"name":"wendu"})

发送FormData:

FormData formData = new FormData.from({
   "name": "wendux",
   "file1": new UploadFileInfo(new File("./upload.pdf"), "upload1.pdf")
});
response = await dio.post("/info", data: formData)

正在下载文件:

response=await dio.download("https://www.google.com/","./xx.html") 

更多详情请参阅Github中的diohttps://github.com/flutterchina/dio