What is the easiest way to get an HTTP response fr

2019-04-08 04:59发布

问题:

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

回答1:

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



回答2:

this is the shortest code i could find

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

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

Here are the other special variables available in case you want to customize the output some 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


标签: dart