Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Curl like functionality in Dart

Tags:

dart

I'm looking for the best way to get curl-like functionality in Dart. For example, how to fetch the google.com web content and output it, as an example.

I found that I can call it via the shell as shown here, however that doesn't seem like the ideal approach:

import 'dart:io';

main() {
  var f = new File(new Options().executable);
  Process.start('curl', 
                ['--dump-header', '/tmp/temp_dir1_M8KQFW/curl-headers', '--cacert',
                 '/Users/ager/dart/dart/third_party/curl/ca-certificates.crt', '--request', 
                 'POST', '--data-binary', '@-', '--header', 'accept: ', '--header', 'user-agent: ' ,
                 '--header', 'authorization: Bearer access token', '--header', 
                 'content-type: multipart/form-data', '--header',
                 'content-transfer-encoding: binary', '--header',
                 'content-length: ${f.lengthSync()}', 'http://localhost:9000/upload']).then((p) {
    f.openInputStream().pipe(p.stdin);
    p.stdout.pipe(stdout);
    p.stderr.pipe(stderr);
    p.onExit = (e) => print(e);
  });
}

I also looked at the API and could not find anything to help me here.

like image 849
stan Avatar asked Dec 23 '12 17:12

stan


1 Answers

Dart IO library comes with a HttpClient which is basically what you are looking for. However, you should probably use the http Pub package instead. Add it to your dependencies file:

dependencies:
  http: any

Run pub install and then just:

import 'package:http/http.dart' as http;

main() {
  http.read('http://google.com').then((contents) {
    print(contents); // Here we output the contents of google.com.
  });
}
like image 198
Kai Sellgren Avatar answered Sep 20 '22 20:09

Kai Sellgren