curl在linux下是一个传输数据工具,可以向服务端提交或获取数据。支持HTTP/HTTPS/FTP/FTPS/TFTP/DICT/TELNET/LDAP/FILE,提供代理、用户验证、ftp上传、SSL连接等功能。curl的传输功能都有libcurl具体实现。
其具体命令行操作可以man curl,下面介绍使用libcurl请求url。
#include <curl/curl.h>
bool GetHttpResult(const string& url, string& result){ cout << "GetHttpResult --> " << url << endl; CURL* handle = NULL; try{ handle = curl_easy_init(); curl_easy_setopt(handle, CURLOPT_NOSIGNAL, 1); curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(handle, CURLOPT_TIMEOUT_MS, 1000);//连接服务器和发送请求的超时设置,单位是毫秒 //curl_easy_setopt(handle, CURLOPT_CONNECTTIMEOUT_MS, 2000); curl_easy_setopt(handle, CURLOPT_WRITEDATA, &result); curl_easy_setopt(handle, CURLOPT_URL, url.c_str());//Get请求 CURLcode ret = curl_easy_perform(handle); curl_easy_cleanup(handle); if ( 0 < ret ){ result.clear(); cout << "Load Url Error! " << url << " ErrorType: " << ret; return false; } } catch (std::exception e){ cout << "Http Request Error!"; curl_easy_cleanup(handle); return false; } return true; }
size_t WriteCallback(void *ptr, size_t size, size_t nmemb, void *data) { string *buff = (string *) data; buff->append((char *) ptr, size * nmemb); return size * nmemb; }
int main() { CURLcode re = curl_global_init( CURL_GLOBAL_ALL ); string url = "http://www.baidu.com"; string result; bool b = GetHttpResult(url, result); if (b) { cout << "success" << endl; cout << result << endl; } else { cout << "fail" << endl; } curl_global_cleanup(); return 1; }
注:
CURLcode curl_global_init(long flags)/curl_global_cleanup(): libcurl库的初始化和关闭,两个函数不是线程安全的,所以要在主线程中进行一次初始化和清除。
参数设置具体解释可以参考http://www.qingfengju.com/article.asp?id=250