libcurl實現https方式下載和訪問
阿新 • • 發佈:2019-01-24
準備條件:
編譯好的libcurl庫,如果要支援https,需要和openssl一起編譯,網上教程較多
示例程式碼:
// libcurtest.cpp : 定義控制檯應用程式的入口點。 // #include "stdafx.h" #include <iostream> #include <windows.h> #include "curl.h" using namespace std; size_t my_write_func( void *ptr, size_t size, size_t nmemb, FILE *stream ) { if( stream != NULL ) return fwrite( ptr, size, nmemb, stream ); else return 0; } //by zhaocl int main() { HMODULE hdll = LoadLibrary( L"libcurl.dll" ); if( !hdll ) { return -1; } typedef CURL * ( *PCURL_EASY_INIT )(); typedef CURLcode( *PCURL_EASY_SETOPT )( CURL*, CURLoption, ... ); typedef CURLcode( *PCURL_EASY_PERFORM )( CURL* ); typedef void( *PCURL_EASY_CLEANUP )( CURL * ); PCURL_EASY_SETOPT pFunction = NULL; PCURL_EASY_PERFORM pFunction2 = NULL; PCURL_EASY_INIT pFunction3 = NULL; PCURL_EASY_CLEANUP pFunction4 = NULL; pFunction3 = ( PCURL_EASY_INIT )GetProcAddress( hdll, "curl_easy_init" ); pFunction = ( PCURL_EASY_SETOPT )GetProcAddress( hdll, "curl_easy_setopt" ); pFunction2 = ( PCURL_EASY_PERFORM )GetProcAddress( hdll, "curl_easy_perform" ); pFunction4 = ( PCURL_EASY_CLEANUP )GetProcAddress( hdll, "curl_easy_cleanup" ); PCURL_EASY_INIT url_ini = ( PCURL_EASY_INIT )( PCURL_EASY_INIT )GetProcAddress( hdll, "curl_easy_init" ); if( !url_ini ) { return -1; } CURL *curl; CURLcode res; //const char* strUrl = "Https://www.baidu.com"; const char* strUrl = "https://slproweb.com/download/Win64OpenSSL-1_0_2o.exe"; curl = url_ini(); //初始化 if( curl && strUrl ) { //下載 FILE *outfile; fopen_s( &outfile, "AxTools.exe", "wb" ); pFunction( curl, CURLOPT_URL, strUrl ); pFunction( curl, CURLOPT_WRITEDATA, outfile ); pFunction( curl, CURLOPT_SSL_VERIFYPEER, false ); //設定為不驗證證書和HOST pFunction( curl, CURLOPT_SSL_VERIFYHOST, false ); pFunction( curl, CURLOPT_WRITEFUNCTION, my_write_func ); pFunction( curl, CURLOPT_NOPROGRESS, FALSE ); pFunction( curl, CURLOPT_PROGRESSFUNCTION, NULL ); pFunction( curl, CURLOPT_PROGRESSDATA, NULL ); res = pFunction2( curl ); fclose( outfile ); /* always cleanup */ pFunction4( curl ); //訪問 pFunction( curl, CURLOPT_URL, strUrl ); //設定url地址 pFunction( curl, CURLOPT_WRITEFUNCTION, my_write_func ); //設定回撥函式 FILE *fp; _wfopen_s( &fp, L"c:\\test.txt", _T( "wb+" ) ); pFunction( curl, CURLOPT_WRITEDATA, fp ); //設定寫資料 pFunction( curl, CURLOPT_SSL_VERIFYPEER, false ); //設定為不驗證證書和HOST pFunction( curl, CURLOPT_SSL_VERIFYHOST, false ); res = pFunction2( curl ); //執行 if( res == CURLE_OK ) { //ok 處理資料 pFunction4( curl ); return 1; } return -1; } return -1; }