全局初始化
libcurl使用之前必須執行全局初始化,只能執行一次。curl_global_cleanup同理curl_global_init(CURL_GLOBAL_ALL);
使用curl_version_info來查看所運行的libcurl細節,看看它支持一些什麼功能
使用easy interface
爲了使用easy interface,必須創建一個easy hadle。CURL *easy_handle = curl_easy_init();
不應該在不同的線程中使用同一個easy_handle
設置handle屬性
通過curl_easy_setopt來設置handle的屬性設置請求鏈接來下載資源
int ret = curl_easy_setopt(easy_handle, CURLOPT_URL, "http://speedtest.wdc01.softlayer.com/downloads/test10.zip");
可以通過curl_easy_reset來重置curl_easy_setopt設置的內容,把它們還原成默認值
設置CURLOPT_VERBOSE爲1L來輸出詳細信息以供調試,如果還不夠,繼續設置CURLOPT_DEBUGFUNCTION
執行網絡請求
上面的一些過程僅僅是設置好了handle的參數,還沒有真正的執行網絡請求。
調用curl_easy_perform將執行網絡請求
ret = curl_easy_perform(easy_handle);
if (ret != CURLE_OK)
{
cout << ret << ":" << curl_easy_strerror(static_cast<CURLcode>(ret)) << endl;
switch (ret)
{
case CURLE_HTTP_RETURNED_ERROR:
{
int code = 0;
curl_easy_getinfo(easy_handle, CURLINFO_RESPONSE_CODE, &code);
printf("HTTP error code:%d\n", code);
break;
}
}
}
curl_easy_perform會返回一個編號來告訴你成功或者失敗,你可以使用CURLcode curl_easy_setopt(CURL *handle, CURLOPT_ERRORBUFFER, char *buf);來獲得更多的錯誤信息
如果想重新發起一個新的請求,官方推薦重複利用這個easy_handle,這樣libcurl會嘗試重複利用先前的連接
curl_easy_pause來暫停或者恢復一個連接
釋放資源
當請求執行完成之後可以釋放掉handle資源
curl_easy_cleanup(easy_handle);
當不再需要發送網絡請求時,釋放全局資源
curl_global_cleanup();
總結
libcurl使用順序
首先初始化全局設置:curl_global_init
初始化easy_handle:curl_easy_init
設置handle的參數:curl_easy_setopt
執行請求:curl_easy_perform
釋放handle:curl_easy_cleanup
釋放全局資源:curl_global_cleanup
libcurl教程:http://www.cnblogs.com/suiyingjie/archive/2012/11/12/2766332.html
libcurl C API:http://curl.haxx.se/libcurl/c/
C++使用libcurl做HttpClient :http://blog.csdn.net/huyiyang2010/article/details/7664201
libcurl curl_multi 非阻塞方式 請求網頁 http:http://blog.sina.com.cn/s/blog_731d783001011tse.html