如何在Dart命令行中执行POST HttpClient [英] How to do POST in Dart command line HttpClient

查看:1223
本文介绍了如何在Dart命令行中执行POST HttpClient的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

开始看起来很简单:

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

问题是:什么是正确的语法和顺序,使 HttpClient

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?

推荐答案

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

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

这篇关于如何在Dart命令行中执行POST HttpClient的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆