从命令行Dart获取HTTP响应最简单的方法是什么? [英] What is the easiest way to get an HTTP response from command-line Dart?
问题描述
我在Dart写了一个命令行脚本。
使用 http包,以便轻松地对HTTP资源进行命令行访问。虽然核心 dart:io
库具有HTTP客户端的原语(请参阅 HttpClient ),http包使GET,POST等更容易。
首先,在您的pubspec依赖项中添加http :
name:sample_app
description:我的示例应用程序。
dependencies:
http:any
安装软件包。在命令行或通过Dart编辑器运行:
pub install
pre>
导入程序包:
// in your app
import'package:http / http.dart'as http;
发出GET请求。
get()
函数返回未来
。http.get('http://example.com/hugs').then((response)=> print(response.body));
最好的做法是使用
get
:未来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
I am writing a command-line script in Dart. What's the easiest way to access (and GET) an HTTP resource?
解决方案Use the http package for easy command-line access to HTTP resources. While the core
dart:io
library has the primitives for HTTP clients (see HttpClient), the http package makes it much easier to GET, POST, etc.First, add http to your pubspec's dependencies:
name: sample_app description: My sample app. dependencies: http: any
Install the package. Run this on the command line or via Dart Editor:
pub install
Import the package:
// inside your app import 'package:http/http.dart' as http;
Make a GET request. The
get()
function returns aFuture
.http.get('http://example.com/hugs').then((response) => print(response.body));
It's best practice to return the Future from the function that uses
get()
:Future getAndParse(String uri) { return http.get('http://example.com/hugs') .then((response) => JSON.parse(response.body)); }
Unfortunately, I couldn't find any formal docs. So I had to look through the code (which does have good comments): https://code.google.com/p/dart/source/browse/trunk/dart/pkg/http/lib/http.dart
这篇关于从命令行Dart获取HTTP响应最简单的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!