用libCURL庫post json資料

2021-09-12 13:39:22 字數 3060 閱讀 6110

libcurl是優秀的c語言版http 庫,時間比較久,目前支援也比較完善,官方網頁見 

對很多協議都有很好的支援。

別的語言都有對http較完善的庫支援, 在c/c++領域libcurl可能是最好用的了吧。我本來是打算用qt裡面的qnetworkmanager,無奈實在是太難用,這一點qt做的實在不怎麼的。

nmake /f makefile.vc mode=static vc=12 debug=yes
編譯relase版本設定debug=no就可以了; 生成兩個檔案:

在builds目錄下找到生成的include和lib目錄用來進行程式開發;在windows下,debug版與release版不能通用。

libcurl_a_debug.lib

libcurl_a.lib

分別將include目錄和lib引入工程,windows平台下qt 的.pro檔案是這樣寫的:

curl標頭檔案放在include/curl目錄下。debug和release用的curl的庫不是同乙個,否則會在執行時出錯。

includepath += \

$$pwd/include \

win32

用靜態鏈結方式的話,必須定義這個巨集。

#define curl_staticlib   //靜態鏈結

#include

curl_easy_init();進行初始化操作

curl_easy_setopt(curl,  a, value);  這個函式用於設定http各個引數

curlopt_debugfunction 指定除錯輸出時呼叫的函式。這裡是ondebug。具體可以參照  中的例子。

curlcode res;  

curl* curl = curl_easy_init();

if (null == curl)

if ( false )//用於除錯的設定

curl_easy_setopt(curl, curlopt_url, strurl.c_str());

curl_easy_setopt(curl, curlopt_post, 1);

curl_easy_setopt(curl, curlopt_postfields, strpost.c_str());

curl_easy_setopt(curl, curlopt_readfunction, null);

curl_easy_setopt(curl, curlopt_writefunction, onwritedata);

curl_easy_setopt(curl, curlopt_writedata, (void *)&strresponse);

curl_easy_setopt(curl, curlopt_nosignal, 1);

curl_easy_setopt(curl, curlopt_connecttimeout_ms, 3000);

curl_easy_setopt(curl, curlopt_timeout, 300);

curl_easy_setopt(curl, curlopt_followlocation, 1); //支援伺服器跳轉

curl_easy_setopt(curl, curlopt_post, 1);//設定為非0表示本次操作為post

res = curl_easy_perform(curl);

//curl_easy_cleanup(curl);

return res;

可以用curl_easy_setopt()函式實現。

二是如果需要保持長連線,需要curlopt_timeout 的設定一定要大於curlopt_tcp_keepidle的設定,或者設定為預設值0(不超時), 否則可能你還沒等到應答就已經超時了。

參考:三是 curl_easy_cleanup(curl); 會釋放資源,如果釋放後再curl_easy_init();傳送資料會重新進行連線,

因此不要執行    curl_easy_cleanup(curl);  下一次傳送資料時,才可以重用連線。

四是用好ondebug函式,可以除錯http傳送過程。

ondebug函式和onwritedata函式如下:

static int ondebug(curl *, curl_infotype itype, char * pdata, size_t size, void *)  

else if(itype == curlinfo_header_in)

else if(itype == curlinfo_header_out)

else if(itype == curlinfo_data_in)

else if(itype == curlinfo_data_out)

return 0;

}

static size_t onwritedata(void* buffer, size_t size, size_t nmemb, void* lpvoid)

char* pdata = (char*)buffer;

return nmemb;

}

參考:  除錯**是從這拿過來的。

libcurl庫的簡單使用

include include include include include include pragma comment lib,ws2 32.lib pragma comment lib,wldap32.lib ifdef debug pragma comment lib,libcurld.l...

使用C 網路庫libcurl

curl global init 和curl global cleanup 這兩個函式並不是執行緒安全的。所以只能在主線程中進行一次的初始化和清除。解決辦法 設定超時 curl easy setopt curl,curlopt timeout,30l 自 libcurl 是乙個很不錯的庫,支援htt...

最全的libcurl庫資源整理

最近在學習libcurl,順便將蒐集的相關資源整理下,方便各位朋友。c 使用libcurl做httpclient libcurl部分總結 libcurl學習筆記 一 curl passing data to a function c curl模擬登陸 curl獲得cookie資料 libcurl 使...