码迷,mamicode.com
首页 > Web开发 > 详细

libcurl 用法

时间:2017-11-04 00:19:12      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:使用   libcurl   

编译使用

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 用法

标签:使用   libcurl   

原文地址:http://fengyuzaitu.blog.51cto.com/5218690/1978746

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!