Networking is essentially a set of unpredictable and asynchronous operations. Let's do it asynchronously in a separate thread to prevent stalls on the UI thread, which may result in ANR behavior on Android.
Here, we need all that we have implemented in the previous recipes of this chapter: smart pointers, worker threads, libcurl downloader, and asynchronous events queue.
We derive the
DownloadTask
class, which performs an HTTP request using the libcurl library, fromiTask
. Here, we implement its methodRun()
, which sets up the libcurl library and performs a network operation:void DownloadTask::Run() { clPtr<DownloadTask> Guard( this ); CURL* C = curl_easy_init();
Setup parameters for libcurl:
curl_easy_setopt( C, CURLOPT_URL, FURL.c_str() ); curl_easy_setopt( C, CURLOPT_FOLLOWLOCATION, 1 ); curl_easy_setopt( C, CURLOPT_NOPROGRESS, false ); curl_easy_setopt( C, CURLOPT_FAILONERROR, true ); curl_easy_setopt(...