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

[亡魂溺海] 提交于 2019-12-05 13:01:08

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

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.
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!