dcli
  • Introduction
  • What does DCli do?
  • Install DCli
    • Installing on Windows
  • Writing your first CLI app
  • Add DCli to your project
  • pub.dev
  • github
  • Dart basics
    • Dart lambda functions
    • Function Arguments
    • Futures
    • stdin/stdout/stderr a primer
  • Tour
    • Overview
    • Using DCli functions
    • User input
      • Ask Validators
    • Displaying information
    • Managing Files And Directories
    • Environment variables
    • Calling apps
    • Redirecting output
    • Command Line Arguments
    • Paths
    • Glob Expansion
    • Piping
    • Locking
    • Fetch
    • The evils of CD
    • Assets/Resources
    • Cross Platform
      • Posix
      • Windows
      • Docker
        • Detecting Docker
        • Add DCli to a Docker Container
        • Example DCli app in Docker
  • Elevated Privileges
    • Sudo
  • Performance
  • Dependency Management
    • Dependency Management
    • Pubspec Managment
  • DCli Tools
    • DCli tools
    • Use a shebang #!
    • DCli Compile
    • DCli Clean
    • DCli Create
    • DCli Doctor
    • DCli Install
    • DCli Run
    • DCli Warmup
    • DCli Pack
    • Upgrade DCli
  • Internal Workings
    • Internal Workings
    • waitForEx
  • Contributing
    • Creating a release
    • Running Unit tests
    • Implemention support for a shell
    • Templates
  • References
  • Examples
    • Projects
    • Code
      • hello world.
      • dcompress
      • dpath
      • dmysql
      • dshell
      • dwhich
      • dipaddr
      • gnome launcher
  • Articles
    • build CLI apps in dart - part 1
    • build CLI apps in dart - part 2
    • Dealing with permissions
    • 3rd Party console packages
  • Dart on Linux - the perfect CLI tooling
  • Improving your build environment
    • Existing tooling
    • Building with Dart
    • A home for your build tools
  • Olivier Revial - CLI apps made easy
  • Video: package of the week
Powered by GitBook
On this page
  • Fetch a single resource
  • Fetch as single resource and show progress
  • Fetch multiple resource and show progress
  • Post data to a server
  • FetchData
  • FetchData.fromString
  • FetchData.fromFile
  • FetchData.fromBytes
  • FetchData.fromStream
  • Custom Headers

Was this helpful?

  1. Tour

Fetch

PreviousLockingNextThe evils of CD

Last updated 2 years ago

Was this helpful?

The fetch command allows you to send and receive data to or from a server.

Fetch supports http and https but where possible you should always use https.

In its simplest form fetch is often used to download a file from a web server however you can also post data to a web server.

For complete API documentation refer to:

DCli allows you to fetch a single web resource with progress information or to simultaneously fetch multiple resources.

Fetch a single resource

The resource 'sample.aac' will be downloaded and saved to the temporary file 'sample.aac'.

withTempFile((sampleAac) {
  try {
        String baseURl =
'https://raw.githubusercontent.com/noojee/dcli/master/test/src/functions/fetch_downloads';
        fetch(url: '$baseURl/sample.aac', saveToPath: sampleAac);
    } on FetchException catch (e) {
      print('Exception Thrown: ${e.errorCode} ${e.message}');
    }
    /// print the returned data including any errors.
    if (exists(tmp)) {
      print(read(tmp).toParagraph());
    }
}, create: false
, suffix: 'acc');

Fetch as single resource and show progress

  withTempFile((sampleAac) {
   try {
       fetch(url: '$baseURl/sample.aac',
            saveToPath: sampleAac,
            onProgress: (progress) {
            print(progress);
       });
    } on FetchException catch (e) {
      print('Exception Thrown: ${e.errorCode} ${e.message}');
    }
    /// print the returned data including any errors.
    if (exists(tmp)) {
      print(read(tmp).toParagraph());
    }
 }, create: false
 , suffix: 'acc');

Fetch multiple resource and show progress

void get() {
  var sampleAac = fs.tempFile();
  var sampleWav = fs.tempFile();

  fetchMultiple(urls: [
          FetchUrl(url: '$baseURl/sample.aac', saveToPath: sampleAac, onProgress: showProgress),
          FetchUrl(url: '$baseURl/sample.wav', saveToPath: sampleWav)
        ]);
}

void showProgress(FetchProgress progress) {
  print(progress);
}

Post data to a server

Send the data contained in the 'content' variable to httpbin.org.

 withTempFile((file) {
     try
     {
        const content = 'Hellow World';
        fetch(
            url: 'https://httpbin.org/post',
            method: FetchMethod.post,
            data: FetchData.fromString(content),
            saveToPath: file);
        /// process the json response.
        final map =
            Parser(read(file).toList()).jsonDecode() as Map<String, dynamic>;
        expect(map['data'] as String, equals(content));
        expect(
            (map['headers'] as Map<String, dynamic>)['Content-Type'] as String,
            equals('text/plain'));
    } on FetchException catch (e) {
      print('Exception Thrown: ${e.errorCode} ${e.message}');
    }
    /// print the returned data including any errors.
    if (exists(file)) {
      print(read(file).toParagraph());
    }
  }, create: false);
      

FetchData

When posting data to a server you can provide the data from a number of different sources using the appropriate FetchData constructor.

FetchData.fromString

Provides data to the fetch method contained in a String.

By default the mimeType is set to text/plain but you can override this by explicitly passing a mimeType

FetchData.fromString('Hello World', mimeType: 'plain.csv');

FetchData.fromFile

The fromFile constructor uses a file as the source of the data to be posted.

By default fromFile will use the filename's extension to determine the mime type.

You can override the default behaviour by passing the mimeType to the constructor

FetchData.fromFile('mountains.png');

FetchData.fromFile('mountains', mimeType: 'image/png');

FetchData.fromBytes

The fromBytes constructor allows you to set the source of data as a byte array.

  withTempFile((pathToData) {
        withTempFile((file) {
          const bytes = <int>[0, 1, 2, 3, 4, 5];

          fetch(
              url: 'https://httpbin.org/post',
              method: FetchMethod.post,
              data: FetchData.fromBytes(bytes),
              saveToPath: file);
        
        }, create: false);
      });

FetchData.fromStream

The fromStream constructor allows you use a stream as the source of the post data.

By default the mimeType is set to 'application/octet-stream' but you can override this by passing an explicit mimeType to FetchData.fromStream.

withTempFile((pathToData) { 
    withTempFile((file) { 
        const content = 'Hellow World2'; 
        pathToData.write(content);  
            
      fetch(
          url: 'https://httpbin.org/post',
          method: FetchMethod.post,
          data: FetchData.fromStream(File(pathToData).openRead()),
          saveToPath: file);
          
    }, create: false);
  });

Custom Headers

The fetch function allows you to set custom HTTP headers.

The 'Content-Type' header will be overridden by the mimeType in FetchData.

   withTempFile((file) {
        fetch(url: 'https://httpbin.org/get',
            headers: {'X-Test-Header1': 'Value1', 'X-Test-Header2': 'Value2'},
            saveToPath: file);
            
      }, create: false);
pub.dev