Mourner63
Mourner63

Reputation: 115

Loading a web page's HTML to a string

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?

Upvotes: 1

Views: 2703

Answers (4)

crash
crash

Reputation: 197

Without error handling:

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();
}

Or if you prefer to use the simpler WebClient class, read: http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx

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

var html = wc.DownloadString(url);

Upvotes: -1

Zdeslav Vojkovic
Zdeslav Vojkovic

Reputation: 14591

I prefer to use HttpBodyHandler for parsing:

  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));

Upvotes: 5

Kai Sellgren
Kai Sellgren

Reputation: 30292

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.

Upvotes: 11

Mourner63
Mourner63

Reputation: 115

While this does not directly show the function I intended to create, it shows the returned HTML printed out, giving the desired effect.

I figured out that this does the trick:

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);
    });
  });
}

If anyone better with Dart can see any issues, don't hesitate to edit.

Upvotes: 1

Related Questions