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; } }
void Http::update() { int running = 0; curl_multi_perform(m_mcurl, &running); CURLMsg *msg; int msgs_left; while ((msg = curl_multi_info_read(m_mcurl, &msgs_left))) { if(msg->msg == CURLMSG_DONE) { int repCode = -1; Downloader *downloader = NULL; curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE, &repCode); curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, &downloader); curl_multi_remove_handle(m_mcurl, msg->easy_handle); downloader->didFinish(msg->data.result, repCode); delete downloader; } } }