Dart HTTP服务器和期货

时间:2014-06-16 13:13:22

标签: dart dart-io dart-async

我正在尝试编写解析client.getUrl()结果的简单HTTP服务器。我已经完成了所有工作,除了我无法回写到http请求对象(打印到控制台工作正常)。

相关代码是:

main() {
  HttpServer.bind(InternetAddress.ANY_IP_V4, 4040)
      .then((HttpServer server) {
    print('listening on localhost, port ${server.port}');
    server.listen((HttpRequest request) {
      Future loadedContent = loadUrl(furl);
      loadedContent.then((content) => print(content));
  //  loadedContent.then((content) => request.response.write(content));

      request.response.close();
      print ("response closed");
    });
  }).catchError((e) => print(e.toString()));
}

问题是主要功能在我从Future获得结果之前结束(通过打印"响应关闭"在结果之前出现第二个)。有没有办法在主函数中等待结果?

修改:它与Dart HttpRequest return future有关 我将重写我的代码,但是如果有一种方法可以在main函数中等待getUrl Future,我会更喜欢它。

编辑:我的loadUrl

Future loadUrl(String url)
{
  final c = new Completer();
  HttpClient client = new HttpClient();
  client.addCredentials(
          Uri.parse("https://*****.tpondemand.com/api"),
          "tprealm",
          new HttpClientBasicCredentials("*****", "*****"));
  client.getUrl(Uri.parse(url))
      .then((HttpClientRequest request) {
        // Optionally set up headers...
        // Optionally write to the request object...
        // Then call close.

        return request.close();
      })
      .then((HttpClientResponse response) {
        // Process the response.
        //print(response.reasonPhrase);
        response.transform(UTF8.decoder).listen((contents) {
             // handle data
            Map parsedMap = JSON.decode(contents);
            c.complete(parsedMap);
            //req.response.write(parsedMap["Items"][0]);
           });

      });
  return c.future;
  }

上次编辑:这是正常工作的代码

import 'dart:io';
import 'dart:async';
import 'package:http_server/http_server.dart';
import 'dart:convert';

final furl = "https://***.tpondemand.com";

Future loadUrlBody(String url) {
  final c = new Completer(); 
  HttpClient client = new HttpClient();
  client.addCredentials(Uri.parse("https://***.tpondemand.com/api"), "tprealm", new HttpClientBasicCredentials("user", "password"));
  client.getUrl(Uri.parse(url))
      .then((HttpClientRequest response) => response.close())
      .then(HttpBodyHandler.processResponse)
      .then((HttpClientResponseBody body) {
       c.complete(body);
      });
  return c.future;
}
main() {
  final filter = "/api/v1/Userstories?format=json&where=(Team.Id+eq+111111)&include=[Name,CreateDate,ModifyDate,LastCommentDate]&take=1000";
  HttpServer.bind(InternetAddress.ANY_IP_V4, 4040).then((HttpServer server) {
    print('listening on localhost, port ${server.port}');
    server.listen((HttpRequest request) {
      print(request.connectionInfo.remoteAddress);
      loadUrlBody(furl + filter).then((content) {
        Map parsedMap = content.body;
        //print("Map parsed");
        request.response.write(parsedMap["Items"]);
        request.response.close();
        //print("response closed");
      }).catchError((e) => print(e.toString()));
    });
  }).catchError((e) => print(e.toString()));
}

1 个答案:

答案 0 :(得分:1)

当你的loadUrl()返回一个Future(可能应该这样)时,这应该可行

main() {
  HttpServer.bind(InternetAddress.ANY_IP_V4, 4040)
      .then((HttpServer server) {
    print('listening on localhost, port ${server.port}');
    server.listen((HttpRequest request) {
      loadUrl(furl).then(() {
        // loadedContent.then((content) => print(content));
        loadedContent.then((content) => request.response.write(content));

        request.response.close();
        print ("response closed");
      });
    });
  }).catchError((e) => print(e.toString()));
} 

<强>更新

您需要修改getData()loadUrl()方法

Future getData(HttpRequest request) { // added return type 'Future' (not necessary)
  return dao.findAll().then((value) { // added 'return'
    print(value);
  });
}

更新2

Future loadUrl(String url)
{
  // final c = new Completer(); // <== commented out
  HttpClient client = new HttpClient();
  client.addCredentials(
          Uri.parse("https://*****.tpondemand.com/api"),
          "tprealm",
          new HttpClientBasicCredentials("*****", "*****"));
  return client.getUrl(Uri.parse(url))                      // <== added return
      .then((HttpClientRequest request) {
        // Optionally set up headers...
        // Optionally write to the request object...
        // Then call close.

        return request.close();
      })
      .then((HttpClientResponse response) {
        // Process the response.
        //print(response.reasonPhrase);
        return response.transform(UTF8.decoder).listen((contents) { // <== added return
             // handle data
            Map parsedMap = JSON.decode(contents);
            // c.complete(parsedMap); // <== commented out
            //req.response.write(parsedMap["Items"][0]);
           }).asFuture();  // <== added `.asFuture()`

      });
   // return c.future; // <== commented out
}

通常,在每次调用返回Future的方法之前添加return就足够了,然后就可以避免使用完成符。 Completer仅适用于更复杂的情况(例如,当您从一个方法返回Completer.future但从其他地方完成它时,例如事件处理程序)。