分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 代码编程

libcurl 用法

发布时间:2023-09-06 01:22责任编辑:顾先生关键词:url

编译使用

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

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

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved