# Include "curl/curl. h" # Pragma comment (lib, "libcurl. lib ")
Long writer (void * data, int size, int nmemb, string & content ); Bool CurlInit (CURL * & curl, const char * url, string & content ); Bool GetURLDataBycurl (const char * URL, string & content ); Void main () { Char * url = "http://www.bKjia. c0m "; String content; If (GetURLDataBycurl (url, content )) { Printf ("% sn", content ); } Getchar (); } Bool CurlInit (CURL * & curl, const char * url, string & content) { CURLcode code; String error; Curl = curl_easy_init (); If (curl = NULL) { Printf ("Failed to create CURL connectionn "); Return false; } Code = curl_easy_setopt (curl, CURLOPT_ERRORBUFFER, error ); If (code! = CURLE_ OK) { Printf ("Failed to set error buffer [% d] n", code ); Return false; } Curl_easy_setopt (curl, CURLOPT_VERBOSE, 1L ); Code = curl_easy_setopt (curl, CURLOPT_URL, url ); If (code! = CURLE_ OK) { Printf ("Failed to set URL [% s] n", error ); Return false; } Code = curl_easy_setopt (curl, CURLOPT_FOLLOWLOCATION, 1 ); If (code! = CURLE_ OK) { Printf ("Failed to set redirect option [% s] n", error ); Return false; } Code = curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, writer ); If (code! = CURLE_ OK) { Printf ("Failed to set writer [% s] n", error ); Return false; } Code = curl_easy_setopt (curl, CURLOPT_WRITEDATA, & content ); If (code! = CURLE_ OK) { Printf ("Failed to set write data [% s] n", error ); Return false; } Return true; } Long writer (void * data, int size, int nmemb, string & content) { Long sizes = size * nmemb; String temp (data, sizes ); Content + = temp; Return sizes; } Bool GetURLDataBycurl (const char * URL, string & content) { CURL * curl = NULL; CURLcode code; String error; Code = curl_global_init (CURL_GLOBAL_DEFAULT ); If (code! = CURLE_ OK) { Printf ("Failed to global init default [% d] n", code ); Return false; }
If (! CurlInit (curl, URL, content )) { Printf ("Failed to global init default [% d] n "); Return PM_FALSE; } Code = curl_easy_perform (curl ); If (code! = CURLE_ OK) { Printf ("Failed to get '% S' [% s] n", URL, error ); Return false; } Long retcode = 0; Code = curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, & retcode ); If (code = CURLE_ OK) & retcode = 200) { Double length = 0; Code = curl_easy_getinfo (curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, & length ); Printf ("% d", retcode ); FILE * file = fopen ("1.gif"," wb "); Fseek (file, 0, SEEK_SET ); Fwrite (content. c_str (), 1, length, file ); Fclose (file ); // Struct curl_slist * list; // Code = curl_easy_getinfo (curl, CURLINFO_COOKIELIST, & list ); // Curl_slist_free_all (list ); Return true; } Else { // Debug1 ("% s n", getStatusCode (retcode )); Return false; } Curl_easy_cleanup (curl ); Return false; } |