Downloading a file
This recipe shows you the simplest ways to download a file through code, first in a command-line application and then from a web application. As an example, we download the front page of the Learning Dart website from http://learningdart.org.
Getting ready
A client program (be it web or command-line) receives content, such as files or web pages, from a web server using the HTTP protocol. The dart:html
and dart:io
package provides us with the basic classes we need to do this, which are as follows:
The
Uriclass
class (fromdart:core
) has all we need to parse, encode, and decode web addresses; the methodUri.parse
is often usedThe
HttpRequest
class (fromdart:html
) has thegetString
method to fetch a file from a URLThe
HttpClientclass
class (fromdart:io
) has all kinds of methods, such asget
andpost
, to send a request (classHttpClientRequest
) to a web server and get a response (classHttpClientResponse
) back
How to do it...
For a web app, this is shown in
download_string.dart...