void Http::Request(const string &url, bool async, bool usePost, const void *data, size_t dataLen, HttpCallback callback, void *callbackArg, map<std::string, string> *header, int timeout) { if( timeout <= 0 ) { timeout = 60; } CURL *handle = curl_easy_init(); Downloader *downloader = new Downloader(handle, callback, callbackArg); curl_easy_setopt(handle, CURLOPT_URL, url.c_str()); curl_easy_setopt(handle, CURLOPT_TIMEOUT, timeout); curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, writer); curl_easy_setopt(handle, CURLOPT_FORBID_REUSE, 1); curl_easy_setopt(handle, CURLOPT_WRITEDATA, downloader); curl_easy_setopt(handle, CURLOPT_PRIVATE, downloader); if( usePost ){ curl_easy_setopt(handle, CURLOPT_POST, 1); curl_easy_setopt(handle, CURLOPT_POSTFIELDSIZE, dataLen); curl_easy_setopt(handle, CURLOPT_COPYPOSTFIELDS, data); } if( header != NULL ) { struct curl_slist *headers = NULL; map<string,string>::const_iterator it = header->begin(); for(; it != header->end(); it++ ) { headers = curl_slist_append(headers, (it->first + ": " + it->second).c_str()); } curl_easy_setopt(handle, CURLOPT_HTTPHEADER, headers); downloader->setHeaders(headers); } if( async ) { curl_multi_add_handle(m_mcurl, handle); int running = 0; curl_multi_perform(m_mcurl, &running); }else { int repCode = -1; CURLcode code = curl_easy_perform(handle); if ( CURLE_OK == code ) { curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &repCode); } downloader->didFinish(code, repCode); delete downloader; } }
int Http::Get(const string &url, string &content, map<std::string, string> *header, int timeout) { if( timeout <= 0 ) { timeout = 60; } CURL *handle = curl_easy_init(); Downloader *downloader = new Downloader(handle); curl_easy_setopt(handle, CURLOPT_URL, url.c_str()); curl_easy_setopt(handle, CURLOPT_TIMEOUT, timeout); curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, writer); curl_easy_setopt(handle, CURLOPT_FORBID_REUSE, 1); curl_easy_setopt(handle, CURLOPT_WRITEDATA, downloader); curl_easy_setopt(handle, CURLOPT_PRIVATE, downloader); if( header != NULL ) { struct curl_slist *headers = NULL; map<string,string>::const_iterator it = header->begin(); for(; it != header->end(); it++ ) { headers = curl_slist_append(headers, (it->first + ": " + it->second).c_str()); } curl_easy_setopt(handle, CURLOPT_HTTPHEADER, headers); downloader->setHeaders(headers); } int repCode = -1; CURLcode code = curl_easy_perform(handle); if ( CURLE_OK == code ) { curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &repCode); } int downloaded = -1; if( repCode == 200 ) { content = downloader->getText(); downloaded = content.size(); } delete downloader; return downloaded; }