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;

}






     本文转自fengyuzaitu 51CTO博客,原文链接:http://blog.51cto.com/fengyuzaitu/1978746,如需转载请自行联系原作者
相关文章
|
8月前
|
存储 网络安全 C++
C++ LibCurl 库的使用方法
LibCurl是一个开源的免费的多协议数据传输开源库,该框架具备跨平台性,开源免费,并提供了包括`HTTP`、`FTP`、`SMTP`、`POP3`等协议的功能,使用`libcurl`可以方便地进行网络数据传输操作,如发送`HTTP`请求、下载文件、发送电子邮件等。它被广泛应用于各种网络应用开发中,特别是涉及到数据传输的场景。
175 0
|
9月前
|
存储 缓存 API
freetype用法
freetype用法
123 0
|
应用服务中间件

热门文章

最新文章