【问题标题】:libcurl http post send data to serverlibcurl http post 发送数据到服务器
【发布时间】:2015-08-17 08:21:00
【问题描述】:
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");

当我在上面运行它时,它给了我错误 我怎样才能传递这个脉冲数据和临时数据??

【问题讨论】:

  • 使用 std::ostream 构建查询 URL。

标签: c++ c libcurl intel-edison


【解决方案1】:

一个可能的 C 解决方案:

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

【讨论】:

  • eclipse 给我警告格式 '%d' 需要匹配的 'int' 参数 [-Wformat=]
  • @parth9966 在我的回答中有一个额外的"。我编辑了答案,现在它是正确的。再试一次。
  • 我通过 pulsedata=70 但在数据库中输入 pulsedata = 1553236
  • @parth9966 请出示pulsedatatempdata 的声明。
  • 对不起,我的错误你的代码正在运行,谢谢迈克尔
【解决方案2】:

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

一个可能的 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 调用全部完成。


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

【讨论】:

    猜你喜欢
    • 2011-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-19
    • 2018-05-07
    • 1970-01-01
    相关资源
    最近更新 更多