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

僤鯓⒐⒋嵵緔 提交于 2019-12-22 06:09:07

问题


I started off by trying to use HTTPRequest in dart:html but quickly realised that this is not possible in a console application. I have done some Google searching but can't find what I am after (only finding HTTP Server), is there a method of sending a normal HTTP request via a console application?

Or would I have to go the method of using the sockets and implement my own HTTP request?


回答1:


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



回答2:


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.
    });


来源:https://stackoverflow.com/questions/17197983/in-a-dart-console-application-is-there-a-library-for-an-http-request-that-doesn

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