What is the easiest way to get an HTTP response from command-line Dart?

dart

Solution

Use the http package for easy command-line access to HTTP resources. While the core `dart:io` library has the primitives for HTTP clients (see HttpClient), the http package makes it much easier to GET, POST, etc.

First, add http to your pubspec's dependencies:

name: sample_app
description: My sample app.
dependencies:
  http: any

Install the package. Run this on the command line or via Dart Editor:

pub install

Import the package:

// inside your app
import 'package:http/http.dart' as http;

Make a GET request. The `get()` function returns a `Future`.

http.get('http://example.com/hugs').then((response) => print(response.body));

It's best practice to return the Future from the function that uses `get()`:

Future getAndParse(String uri) {
  return http.get('http://example.com/hugs')
      .then((response) => JSON.parse(response.body));
}

Unfortunately, I couldn't find any formal docs. So I had to look through the code (which does have good comments): https://code.google.com/p/dart/source/browse/trunk/dart/pkg/http/lib/http.dart

Problem

I am writing a command-line script in Dart. What's the easiest way to access (and GET) an HTTP resource?

Original source