標籤: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 基本使用