Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dart

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

like image 773
Seth Ladd Avatar asked Mar 31 '13 20:03

Seth Ladd


People also ask

Which of the following code of command is used to print line of text in Dart?

writeln(line); The write() and writeln() methods take an object of any type, convert it to a string, and print it. The writeln() method also prints a newline character. dcat uses the write() method to print the line number so the line number and text appear on the same line.


1 Answers

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

like image 197
Seth Ladd Avatar answered Oct 08 '22 15:10

Seth Ladd