【问题标题】:Access http response body from outside从外部访问 http 响应体
【发布时间】:2015-03-22 03:08:56
【问题描述】:
import 'package:http/http.dart' as http;

main() {

  String esearch = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=nucleotide&term=Paenibacillus";
  var uidList = [];

  http.get(esearch).then((response) {

    var pattern = new RegExp(r"<Id>(.*?)</Id>");
    var hits = pattern.allMatches(response.body);


    hits.forEach((hit) {
      print("whole match: " + hit[0] + " first match " + hit[1]);
      uidList.add(hit[1]);
    });
  });

  print(uidList.length); // empty, because main thread is faster than query
}

大家好,

我从一天开始就在玩 Dart,想弄清楚它是否适合我的需求。在我附加的代码中,我想访问 http 查询块之外的正文结果。这是不可能的。在这里的另一个问题中,有人写这是因为 Darts 异步概念。

有没有办法从外部访问。这是导入的,因为我必须使用结果数据触发多个 html 请求,并且不会将它们全部嵌套在 http 块中。

或者有什么其他建议?

非常感谢。

【问题讨论】:

    标签: dart dart-async dart-http


    【解决方案1】:

    这不起作用,因为异步调用 (http.get()) 被安排在以后执行,然后执行将继续下一行。你的printhttp.get() 甚至开始连接之前执行。您需要将所有连续调用与 then 链接起来。 如果你有最新的 Dart 版本,你可以使用 async/await,这使得使用异步调用更容易。

    import 'package:http/http.dart' as http;
    
    main() {
    
      String esearch = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=nucleotide&term=Paenibacillus";
      var uidList = [];
    
      return http.get(esearch).then((response) {
    
        var pattern = new RegExp(r"<Id>(.*?)</Id>");
        var hits = pattern.allMatches(response.body);
    
    
        hits.forEach((hit) {
          print("whole match: " + hit[0] + " first match " + hit[1]);
          uidList.add(hit[1]);
        });
        return uidList;
      }).then((uidList) {
        print(uidList.length); 
      });
    }
    

    异步/等待

    import 'package:http/http.dart' as http;
    
    main() async {
    
      String esearch = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=nucleotide&term=Paenibacillus";
      var uidList = [];
    
      var response = await http.get(esearch);
      var pattern = new RegExp(r"<Id>(.*?)</Id>");
      var hits = pattern.allMatches(response.body);
    
      hits.forEach((hit) {
        print("whole match: " + hit[0] + " first match " + hit[1]);
        uidList.add(hit[1]);
      });
      print(uidList.length); 
    }
    

    【讨论】:

      猜你喜欢
      • 2021-02-16
      • 2018-03-18
      • 1970-01-01
      • 1970-01-01
      • 2017-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多