libcurl 基本使用

來源:互聯網
上載者:User

標籤:libcurl post

編譯使用

https://my.oschina.net/u/1420791/blog/198247


當前例子調用libcurl發送Post請求,但是在其中調用UrlEncode函數對發送的Post資料進行了編碼,因為指定了application/x-www-form-urlencoded編碼格式,說明libcurl並沒有提供一個方法進行urlencode編碼,這個需要注意

size_t write_data(void *buffer, size_t size, size_t nmemb, void *userp)

{

ofstream ofs;

ofs.open("reponse.html");

string str = (char*)buffer;

ofs << str << endl;

return 0;

}

int TestCurlPost()

{

CURL* curl;

CURLcode res;


FILE *fptr;

struct curl_slist *http_header = NULL;


if ((fptr = fopen(FILENAME, "w")) == NULL) {

fprintf(stderr, "fopen file error: %s\n", FILENAME);

return -1;

}


Json::Value jsonLoginContext;

jsonLoginContext["loginAccount"] = "admin";


Json::Value jsonParamContext;

jsonParamContext["a"] = 1;

jsonParamContext["b"] = 2;

jsonParamContext["c"] = 3;

Json::Value jsonParm;

jsonParm.append(jsonParamContext);


std::string strPostData= "authorJson=";

strPostData += jsonLoginContext.toStyledString();

strPostData += "&parmJson=";

strPostData += jsonParamContext.toStyledString();


Json::Value json;

json["authorJson"] = "username";


Json::FastWriter writer;

std::string strResult = UrlEncode(strPostData);

char szSendBuffer[1024] = { 0 };

strcpy(szSendBuffer, strResult.c_str());

curl = curl_easy_init();

if (curl)

{

curl_easy_setopt(curl, CURLOPT_URL, "http://120.177.55.115:8089/cs/restfull/operationRestfullApi/testPost");

curl_easy_setopt(curl, CURLOPT_POST, 1);

curl_easy_setopt(curl, CURLOPT_POSTFIELDS, szSendBuffer);

curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);

curl_easy_setopt(curl, CURLOPT_WRITEDATA, fptr);


curl_slist *plist1 = curl_slist_append(NULL,

"Content-Type: application/x-www-form-urlencoded; charset=UTF-8");


curl_easy_setopt(curl, CURLOPT_HTTPHEADER, plist1);

res = curl_easy_perform(curl);

if (res != CURLE_OK)

{

return -1;

}

}

return 0;

}


libcurl 基本使用

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.