【发布时间】:2015-08-09 14:57:38
【问题描述】:
我需要一个可重用的函数,它发出 HTTP 请求并等待其完成,然后将响应作为字符串返回。
主要功能如下:
main() async {
var json;
json = await makeRequest('https://...');
print(json);
print('*** request complete ***');
}
(第一种情况)这是发出 HTTP 请求的可重用函数:
makeRequest(String url) async {
var request = await new HttpClient().postUrl(Uri.parse(url));
// Includes the access token in the request headers.
request.headers.add(...);
// Waits until the request is complete.
var response = await request.close();
await for (var contents in response.transform(UTF8.decoder)) {
return contents;
}
}
这按预期工作,输出是:
// Response contents as a String...
*** request complete ***
(第二种情况)然后我尝试这样做,但没有成功:
makeRequest(String url) async {
var request = await new HttpClient().postUrl(Uri.parse(url));
// Includes the access token in the request headers.
request.headers.add(...);
// Waits until the request is complete.
var response = await request.close();
var json = '';
await response.transform(UTF8.decoder).listen((contents) {
// At first I tried to return contents here, but then I added onDone().
json += contents;
}, onDone: () {
return json;
});
return json;
}
我尝试在listen 中使用async 和await 定义函数,在listen 中返回contents 而没有onDone(),但输出是相同的:
// Empty line.
*** request complete ***
// Waits a few seconds doing nothing before terminating...
有谁知道为什么第二种情况不起作用?
编辑:
更新代码后,它会做它应该做的事情,但在终止执行之前需要几秒钟:
Future<String> twitterRequest(String url) async {
var request = await new HttpClient().postUrl(Uri.parse(url));
// Includes the access token in the request headers.
request.headers.add(...);
// Waits until the request is complete.
var response = await request.close();
var json = '';
await for (var contents in response.transform(UTF8.decoder)) {
json += contents;
// Putting a break here produces the same output but terminates immediately (as wanted).
}
return json;
}
输出:
// Prints response contents...
*** request complete ***
// Takes a few seconds before execution terminates. With the break the code terminates immediately.
EDIT2:
提交this issue on GitHub后,我发现HttpClient的实例有一个连接池并且默认保持持久连接,这使得Dart VM保持活跃。请查阅问题页面以了解可能的解决方案。
【问题讨论】:
标签: dart httprequest dart-async dart-http