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

I am writing a command line script in Dart. What is the easiest way to access (and get) an HTTP resource?

+6
source share
2 answers

Use the http package to simplify access to HTTP resources using the command line. Although the dart:io core library has primitives for HTTP clients (see HttpClient ), the http package makes GET, POST, etc. easier.

First add http to your pubspec dependencies:

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

Install the package. Run this on the command line or using the 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 is best to return the future from a function using get() :

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

Unfortunately, I could not find any official documents. So I had to view the code (which has good comments): https://code.google.com/p/dart/source/browse/trunk/dart/pkg/http/lib/http.dart

+8
source

this is the shortest code i could find

 curl -sL -w "%{http_code} %{url_effective}\\n" "URL" -o /dev/null 

Here, -s silences the progress of curl, -L follows all redirects as before, -w prints the report using a custom format, and -o redirects the output of the HTML cursor to / dev / null.

Here are other special variables available if you want to customize the output a bit more:

  • url_effective
  • HTTP_CODE
  • http_connect
  • time_total
  • time_namelookup
  • time_connect
  • time_pretransfer
  • time_redirect
  • time_starttransfer
  • size_download
  • size_upload
  • size_header
  • size_request
  • speed_download
  • speed_upload
  • content_type
  • num_connects
  • NUM_REDIRECTS
  • ftp_entry_path
0
source

All Articles