Dart HTTPClient响应查询

时间:2014-05-22 16:37:39

标签: dart httpclient synchronous

我想使以下功能同步。 " onDataLoaded"需要在完全读取流后调用。请建议需要做哪些更改。

String JsonContent="";

new HttpClient().getUrl(Uri.parse(uri))
  .then((HttpClientRequest request) 
   {
      request.headers.removeAll(HttpHeaders.ACCEPT_ENCODING);          
      return request.close();
   })
  .then((HttpClientResponse response) 
   {   
      response.transform(UTF8.decoder).listen((contents) {
        JsonContent = contents.toString();  
        print(JsonContent);
        //onDataLoaded(JsonContent); 
      });          
   });

1 个答案:

答案 0 :(得分:2)

这应该有效

import 'dart:io';
import 'dart:convert' show UTF8;

void main(args) {
String JsonContent="";

new HttpClient().getUrl(Uri.parse(uri))
  .then((HttpClientRequest request)
   {
      request.headers.removeAll(HttpHeaders.ACCEPT_ENCODING);
      return request.close();
   })
  .then((HttpClientResponse response)
   {
      response.transform(UTF8.decoder).listen((contents) {
        JsonContent = contents.toString();
        print(JsonContent);
        //onDataLoaded(JsonContent);
      }, onDone: () => onDataLoaded(JsonContent));
   });

}

void onDataLoaded(String jsonContent) {
  print(jsonContent);
}