有没有简单的方法来与dart:io
做到这一点?将网页的HTML加载到字符串
我已经查看了HttpClient和HttpServer,但是我还没有设法创建一个函数,它可以带一个URL并返回一个网站标记的字符串。
String getHtml(String URL) {
...
}
任何人都可以指出我在正确的方向使用什么API?
有没有简单的方法来与dart:io
做到这一点?将网页的HTML加载到字符串
我已经查看了HttpClient和HttpServer,但是我还没有设法创建一个函数,它可以带一个URL并返回一个网站标记的字符串。
String getHtml(String URL) {
...
}
任何人都可以指出我在正确的方向使用什么API?
我更喜欢使用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));
这看起来好多了,谢谢! – Mourner63
没有错误处理:
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);
尽管这并不直接表明我打算创造,它的功能显示返回的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);
});
});
}
如果有人用飞镖更好的可以看到的任何问题,请不要犹豫,编辑。
您是否尝试过的http
包?添加到您的pubspec.yaml文件:
dependencies:
http: any
然后安装包,并使用它像这样:
import 'package:http/http.dart' as http;
main() {
http.read('http://google.com').then((contents) {
print(contents);
});
}
他们也有其他的方法,如post
,get
,head
等,为更方便常用。
看看这个答案。 http包比原始dart更易于使用:io类。 http://stackoverflow.com/a/14013100/1460491 –