Use Libcurl to download files for small cases

Source: Internet
Author: User

Libcurl is a powerful open source network processing library that supports HTTP, HTTPS, FTP ... A range of network protocols. Using it for HTTP get\post or download files is a piece of cake, the chrome kernel has used it, this article mainly on a use Curl download file of the small example.

The first is to download the latest Curl source code, and then compile into a dynamic library or a static library, and then put the head files and library files to join our own project, the reference statement:

" curl.h "   #ifdef _DEBUG  #pragma comment (lib, ". /debug/libcurld ")  #else  #pragma comment (lib,". /release/libcurl ")  #endif  

Deliberately added some comments on the original code, hoping to better understand the code:

<pre name="Code" class="CPP">//UseLibCurl.cpp: Defines the entry point of the console application. //  #include"stdafx.h"#include<Windows.h>#include<CommCtrl.h>#include"resource.h"#include"curl.h"#ifdef _DEBUG#pragmaComment (lib, "... /debug/libcurld ")#else  #pragmaComment (lib, "... /release/libcurl ")#endif      //This is the window handle to Save the dialog box, because the window handle must be known after the message is sent to the windowHWND G_hdlgwnd =NULL; //provides a function to curl download progress callback for saving downloaded data to a fileStaticsize_t Downloadcallback (void* pbuffer, size_t nSize, size_t nmembyte,void*pparam); //a function for curl download progress callback to calculate the download Progress notification interfaceStatic intProgresscallback (void*CLIENTP,DoubleDltotal,DoubleDlnow,DoubleUltotalDoubleUlnow); //This is the message loop of the dialog box, creating a GUI in the console program, just to better show the download callback functionint_ptr CALLBACK DialogProc (HWND hwnd, UINT umsg, WPARAM WPARAM, LPARAM LPARAM); //This is the download of the thread function, in order not to put the main interface of the dialog box to die, must be a self-threading downloadDWORD WINAPI downloadthread (LPVOID lpparam); int_tmain (intARGC, _tchar*argv[]) {      //Pop-up dialog box, knowing that the dialog closes before execution exitsdialogbox (NULL, Makeintresource (IDD_DIALOG1), NULL, DIALOGPROC); return 0; }    Staticsize_t Downloadcallback (void* pbuffer, size_t nSize, size_t nmembyte,void*pparam) {      //append the downloaded data to the file (must have a, otherwise the previously written content will be overwritten)file* fp =NULL; Fopen_s (&AMP;FP,"c:\\test.apk","ab+"); size_t Nwrite=fwrite (pbuffer, NSize, Nmembyte, FP);      Fclose (FP); returnNwrite; }    Static intProgresscallback (void*CLIENTP,DoubleDltotal,DoubleDlnow,DoubleUltotalDoubleUlnow) {      if(Dltotal >-0.1&& Dltotal <0.1 )          return 0; intNPos = (int) ((dlnow/dltotal) * - ); //Notification progress bar update download Progress::P ostmessage (G_hdlgwnd, Wm_user + the, NPos,0); //:: Sleep (10);     return 0; } INT_PTR CALLBACK DialogProc (HWND hwnd, UINT umsg, WPARAM WPARAM, LPARAM LPARAM) {Switch(umsg) { Casewm_initdialog: {g_hdlgwnd=hWnd; HWND hprogress=GetDlgItem (hWnd, IDC_PROGRESS1); SendMessage (Hprogress, Pbm_setrange32, (WPARAM)0, (LPARAM) -); //Create a download thread when the dialog box is initializedHANDLE hthread = CreateThread (NULL,0, Downloadthread,0,0, NULL);              CloseHandle (Hthread); :: SetWindowText (hWnd, L"examples of downloading files using curl:"); returnTRUE; }       Casewm_command: {WORD msg=HiWord (WParam); WORD ID=LoWord (WParam); if(id = = IDOK | | id = =IDCANCEL)              EndDialog (hWnd, id);  Break; }       CaseWM_ERASEBKGND:returnTRUE;  Casewm_ctlcolorstatic:return( int_ptr) (hbrush):: Getstockobject (White_brush);  CaseWm_user + the:          {//receive message to set progressHWND hprogress =GetDlgItem (hWnd, IDC_PROGRESS1); HWND Hstatus=GetDlgItem (hWnd, idc_status); if(hprogress) SendMessage (hprogress, Pbm_setpos, WParam,0L); if(hstatus) {WCHAR szbuffer[ -] = {0}; if(wparam< -) swprintf (szbuffer, L"downloading file, progress:%d%%", WParam); Elseswprintf (szbuffer, L"File Download complete! ");              :: SetWindowText (Hstatus, szbuffer); }              return 0; }      default:           Break; }      returnDefWindowProc (hWnd, umsg, WParam, LParam); } DWORD WINAPI Downloadthread (lpvoid lpparam) {//Initialize curl, this is a must.curl* Curl =Curl_easy_init (); Curl_easy_setopt (Curl, Curlopt_url,"http://android.shoujids.com/software/download?id=154103"); //set callback to receive datacurl_easy_setopt (Curl, curlopt_writefunction, downloadcallback); //curl_easy_setopt (Curl, curlopt_infilesize, lfilesize); //curl_easy_setopt (Curl, Curlopt_header, 1); //curl_easy_setopt (Curl, curlopt_nobody, 1); //curl_easy_setopt (Curl, curlopt_nosignal, 1); //to set the maximum number of redirectsCurl_easy_setopt (Curl, Curlopt_maxredirs,5); //set 301, 302 jump following locationCurl_easy_setopt (Curl, Curlopt_followlocation,1); Curl_easy_setopt (Curl, curlopt_noprogress,0); //set the progress callback functioncurl_easy_setopt (Curl, curlopt_progressfunction, progresscallback); //curl_easy_getinfo (Curl, Curlinfo_content_length_download, &lfilesize); //curl_easy_setopt (Curl, Curlopt_progressdata, G_hdlgwnd); //Start Execution RequestCurlcode Retccode =curl_easy_perform (Curl); //See if there is an error message    Const Char* Perror =Curl_easy_strerror (Retccode); //clean curl, and match the previous initializationcurl_easy_cleanup (Curl); return 0; }  

Original link: Use libcurl download File Small example

Use Libcurl to download files for small cases

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.