我正在用 Dart 编写一个命令行脚本。访问(和获取)HTTP 资源的最简单方法是什么?
最佳答案
使用 http package以便通过命令行轻松访问 HTTP 资源。而芯dart:io
库具有 HTTP 客户端的原语(请参阅 HttpClient ),http 包使 GET、POST 等操作变得更加容易。
首先,将 http 添加到您的 pubspec 的依赖项中:
name: sample_app
description: My sample app.
dependencies:
http: any
安装软件包。在命令行或通过 Dart 编辑器运行:
pub install
导入包:
// inside your app
import 'package:http/http.dart' as http;
发出 GET 请求。
get()
函数返回 Future
.http.get('http://example.com/hugs').then((response) => print(response.body));
最好的做法是从使用
get()
的函数中返回 Future :Future getAndParse(String uri) {
return http.get('http://example.com/hugs')
.then((response) => JSON.parse(response.body));
}
不幸的是,我找不到任何正式的文档。所以我不得不查看代码(其中确实有很好的注释):https://code.google.com/p/dart/source/browse/trunk/dart/pkg/http/lib/http.dart
关于dart - 从命令行 Dart 获取 HTTP 响应的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15734057/