Libcurl HTTP post发送数据到服务器

libcurl http post send data to server

本文关键字:数据 服务器 HTTP post Libcurl      更新时间:2023-10-16
curl_easy_setopt(curl, CURLOPT_URL, "127.0.0.1:8081/get.php");
curl_easy_setopt(curl, CURLOPT_POSTFIELDS,"pulse=70 & temp=35" );

上面的代码运行成功,但是当我传入这个

int pulsedata = 70;
int tempdata  = 35;
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "pulse=pulsedata & temp = tempdata");

当我运行上面这行时,它给我错误我怎么能传递这个脉冲数据和tempdata ??

一个可能的C解决方案:

char sendbuffer[100];
snprintf(sendbuffer, sizeof(sendbuffer), "pulse=%d&temp=%d", pulsedate, tempdata);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, sendbuffer);

你不能在这样的字符串中使用变量,你必须格式化字符串。

一个可能的c++解决方案是像这样使用std::ostringstream:
std::ostringstream os;
os << "pulse=" << pulsedata << "&temp=" << tempdata;
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, os.str().c_sr());

使用这种解决方案,std::ostringstream对象(在我的示例中是os)需要在CURL调用全部完成之前保持活动。


还要注意,我构造的查询字符串不包含任何空格。

相关文章: