Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a Dart console application, is there a library for an HTTP Request that doesnt require DOM access?

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?

like image 955
Tom C Avatar asked Jun 19 '13 17:06

Tom C


2 Answers

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
like image 89
Darshan Rivka Whittle Avatar answered Sep 26 '22 14:09

Darshan Rivka Whittle


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.
    });
like image 20
Chris Buckett Avatar answered Sep 24 '22 14:09

Chris Buckett