1

这是一个问题。当我运行这些代码时:

String responseText = null;

HttpRequest.getString(url).then((resp) {
    responseText = resp;
    print(responseText);
    });
print(responseText);

在控制台中:

{"meta":{"code":200},"data":{"username":"kevin","bio":"CEO \u0026 Co-founder of Instagram","website":"","profile_picture":"http:\/\/images.ak.instagram.com\/profiles\/profile_3_75sq_1325536697.jpg","full_name":"Kevin Systrom","counts":{"media":1349,"followed_by":1110365,"follows":555},"id":"3"}}
null

它异步运行。有同步方法的JAVA方式吗?请求完成时会等待吗?我只发现了一种棘手的方法,而且很有趣——等待三秒钟:

handleTimeout() {
    print(responseText);
}
const TIMEOUT = const Duration(seconds: 3);
new Timer(TIMEOUT, handleTimeout);

当然,它适用于错误。那么有什么建议吗?

MattB 方式运作良好:

  var req = new HttpRequest();
  req.onLoad.listen((e) {
     responseText = req.responseText;
     print(responseText);
   });
   req.open('GET', url, async: false);
   req.send();
4

1 回答 1

3

首先,我假设您将其用作客户端脚本而不是服务器端。使用 HttpRequest.getString 将严格返回 Future (异步方法)。

如果您绝对必须有一个同步请求,您可以构造一个新的 HttpRequest 对象并调用传递命名参数的open方法:async: false

var req = new HttpRequest();
req.onLoad.listen((e) => print(req.responseText));
req.open('GET', url, async: false);
req.send();

但是,强烈建议您使用异步方法访问网络资源,因为像上面这样的同步调用会导致脚本阻塞,并可能使您的页面/脚本在网络连接不佳时停止响应。

于 2014-04-25T16:53:47.953 回答