1

Is there an easy way to do this with dart:io?

I've looked into HttpClient and HttpServer, but I haven't managed to create a function that can take a URL and return a String of the website's markup.

String getHtml(String URL) {
...
}

Can anyone point me in the right direction as to what API to use for this?

4

4 回答 4

10

Have you tried the http package? Add to your pubspec.yaml file:

dependencies:
  http: any

Then install the package and use it like this:

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

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

They also have other methods like post, get, head, etc. for much more convenient common use.

于 2013-06-05T10:17:38.483 回答
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));
于 2013-06-04T21:16:27.650 回答
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);
    });
  });
}

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

于 2013-06-04T19:52:28.377 回答
-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);
于 2013-06-04T19:30:37.393 回答