2013-06-04 20 views
0

有没有简单的方法来与dart:io做到这一点?将网页的HTML加载到字符串

我已经查看了HttpClient和HttpServer,但是我还没有设法创建一个函数,它可以带一个URL并返回一个网站标记的字符串。

String getHtml(String URL) { 
... 
} 

任何人都可以指出我在正确的方向使用什么API?

+1

看看这个答案。 http包比原始dart更易于使用:io类。 http://stackoverflow.com/a/14013100/1460491 –

回答

5

我更喜欢使用HttpBodyHandler解析:

HttpClient client = new HttpClient(); 
    client.getUrl(Uri.parse("http://www.example.com/")) 
    .then((HttpClientRequest response) => response.close()) 
    .then(HttpBodyHandler.processResponse) 
    .then((HttpClientResponseBody body) => print(body.body)); 
+0

这看起来好多了,谢谢! – Mourner63

-1

没有错误处理:

var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); 

request.Method = "GET"; 
request.AllowAutoRedirect = false; 
request.KeepAlive = true; 
request.ContentType = "text/html"; 

    /// Get response from the request     

using (var response = (System.Net.HttpWebResponse)request.GetResponse()) { 
    System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream()); 
    return reader.ReadToEnd(); 
} 

或者,如果你喜欢使用简单的WebClient类,阅读:http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx

System.Net.WebClient wc = new System.Net.WebClient(); 

var html = wc.DownloadString(url); 
+1

对不起,如果它不够清楚,我希望有一个飞镖特定的反应,因此飞镖标签。 – Mourner63

+0

应该注意到标签;您的代码发布可能是C#或几乎其他任何东西。 – crash

0

尽管这并不直接表明我打算创造,它的功能显示返回的HTML打印出来,给出所需的效果。

我想通了,该做的伎俩:

import 'dart:io'; 
import 'dart:async'; 

main() { 
    HttpClient client = new HttpClient(); 
    client.getUrl(Uri.parse("http://www.example.com/")) 
    .then((HttpClientRequest request) { 
    // Prepare the request then call close on it to send it. 
    return request.close(); 
    }) 
    .then((HttpClientResponse response) { 
    Stream<String> html = new StringDecoder().bind(response); 
    html.listen((String markup) { 
     print(markup); 
    }); 
    }); 
} 

如果有人用飞镖更好的可以看到的任何问题,请不要犹豫,编辑。

6

您是否尝试过的http包?添加到您的pubspec.yaml文件:

dependencies: 
    http: any 

然后安装包,并使用它像这样:

import 'package:http/http.dart' as http; 

main() { 
    http.read('http://google.com').then((contents) { 
    print(contents); 
    }); 
} 

他们也有其他的方法,如postgethead等,为更方便常用。