5

I started off by trying to use HTTPRequest in dart:html but quickly realised that this is not possible in a console application. I have done some Google searching but can't find what I am after (only finding HTTP Server), is there a method of sending a normal HTTP request via a console application?

Or would I have to go the method of using the sockets and implement my own HTTP request?

Darshan Rivka Whittle
  • 32,989
  • 7
  • 91
  • 109
Tom C
  • 822
  • 7
  • 27

2 Answers2

11

There's an HttpClient class in the IO library for making HTTP requests:

import 'dart:io';

void main() {
  HttpClient client = new HttpClient();
  client.getUrl(Uri.parse("http://www.dartlang.org/"))
    .then((HttpClientRequest request) {
        return request.close();
      })
    .then(HttpBodyHandler.processResponse)
    .then((HttpClientResponseBody body) {
        print(body.body);
      });
}

Update: Since HttpClient is fairly low-level and a bit clunky for something simple like this, the core Dart team has also made a pub package, http, which simplifies things:

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

void main() {
  http.get('http://pub.dartlang.org/').then((response) {
    print(response.body);
  });
}

I found that the crypto package was a dependency, so my pubspec.yaml looks like this:

name: app-name
dependencies:
  http: any
  crypto: any
Darshan Rivka Whittle
  • 32,989
  • 7
  • 91
  • 109
2

You'll be looking for the HttpClient which is part of the server side dart:io SDK library.

Example taken from the API doc linked to above:

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) {
      // Process the response.
    });
Chris Buckett
  • 13,738
  • 5
  • 39
  • 46
  • Thank you must have missed that, I guess I should probably pay closer attention to the documentation! Sorry, marked Darshans comment as answer because he was a few seconds earlier. – Tom C Jun 19 '13 at 18:20
  • I noticed that we both gave the same answer within seconds of eachother :) – Chris Buckett Jun 20 '13 at 08:57
  • Not wanting to create another question but Im having a little issue. According to the docs it says there is a setter/getter `userAgent`. However whenever I try `client.userAgent = 'Test';` Dart tells me that it has no setter/getter by that name. Am I reading the documentation wrong or is that supposed to work? – Tom C Jun 20 '13 at 16:30