使用http包可以轻松命令行访问HTTP资源.虽然核心dart:io库具有HTTP客户端的原语(请参阅HttpClient),但http包使得GET,POST等更容易.
首先,将http添加到pubspec的依赖项中:
name: sample_app
description: My sample app.
dependencies:
http: any
Run Code Online (Sandbox Code Playgroud)
安装包.在命令行或Dart编辑器上运行:
pub install
Run Code Online (Sandbox Code Playgroud)
导入包:
// inside your app
import 'package:http/http.dart' as http;
Run Code Online (Sandbox Code Playgroud)
发出GET请求.该get()函数返回一个Future.
http.get('http://example.com/hugs').then((response) => print(response.body));
Run Code Online (Sandbox Code Playgroud)
最佳做法是从使用get()以下功能返回Future :
Future getAndParse(String uri) {
return http.get('http://example.com/hugs')
.then((response) => JSON.parse(response.body));
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,我找不到任何正式的文档.所以我必须查看代码(确实有很好的评论):https://code.google.com/p/dart/source/browse/trunk/dart/pkg/http/lib/http.dart
| 归档时间: |
|
| 查看次数: |
1418 次 |
| 最近记录: |