如何简单地以字符串的形式同步获取一个url体 [英] how to simply fetch an url body as a string synchronously
问题描述
您如何简单实现此函数:
How would you simply implement this function:
String fetchUrlBodyAsString(String url) {
...
}
用法:
String schema = fetchUrlBodyAsString("http://json-schema.org/draft-04/schema#");
此主题使用dart下载文件解释了从主函数获取数据的好方法。但如果你尝试它,你看到真正的工作发生后离开主。我认为我想创建的同步函数很难使用HttpClient,因为它试图让异步api同步工作。根据此线程可能无法实现: https:/ /groups.google.com/a/dartlang.org/d/msg/misc/kAgayQyaPhQ/wonJ776_FGIJ
This thread Using dart to download a file explains a good way to get to the data from a main function. But if you try it you see that the real work happens after leaving main. I think that the synchronous function that I want to create is difficult using HttpClient because it is trying to get an async api to work synchronously. According to this thread that may not be possible: https://groups.google.com/a/dartlang.org/d/msg/misc/kAgayQyaPhQ/wonJ776_FGIJ
什么是Dart的实现方式非浏览器/控制台设置?
What is a Dart way to implement this in a non-browser/console setting?
推荐答案
使用异步方法真的很有感染力。一旦你开始在函数中使用 Future
,你必须返回一个 Future
作为结果。因此,您的 fetchUrlBodyAsString
函数可以如下所示:
The using of asynchronous methods is really infectious. Once you start using Future
inside a function you have to return a Future
as result. So your fetchUrlBodyAsString
function can look like :
import 'dart:io';
import 'dart:async';
Future<String> fetchUrlBodyAsString(String url) =>
new HttpClient().getUrl(Uri.parse(url))
.then((HttpClientRequest request) => request.close())
.then((HttpClientResponse response) =>
response.transform(new StringDecoder()).join());
main() {
final url = "http://json-schema.org/draft-04/schema#";
Future<String> schema = fetchUrlBodyAsString(url);
schema.then(handleContent);
}
handleContent(String content) {
print(content); // or do what you want with content.
}
这篇关于如何简单地以字符串的形式同步获取一个url体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!