C++ Curl 后动态变量

标签 c++ curl post

我想在 POST curl 中使用动态变量
我使用这段代码:

int send(const char*s)
{
  CURL *curl;
  CURLcode res;


  curl_global_init(CURL_GLOBAL_ALL);
  curl = curl_easy_init();
  if(curl) {
    curl_easy_setopt(curl, CURLOPT_URL, "http://localhost/query.php");
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "q=" + s);
    res = curl_easy_perform(curl);

    if(res != CURLE_OK)
      fprintf(stderr, "curl_easy_perform() failed: %s\n",
              curl_easy_strerror(res));

    curl_easy_cleanup(curl);
  }
  curl_global_cleanup();
  std::cout << std::endl << "Query sent" << std::endl;
  return 0;
}

我得到这个错误:

test.cpp:199:57: error: invalid operands of types ‘const char [3]’ and ‘const char*’ to binary ‘operator+’
         curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "q=" + s);
                                                    ~~~~~^~~

最佳答案

必须自己拼接"q="s,Cpp中没有操作符+将chars数组与指针拼接到字符。用"q="创建字符串,将s指向的数据添加到这个字符串中,调用c_str()得到const char* 指针作为 curl_easy_setopt 函数的参数:

#include <string>
....
curl_easy_setopt(curl, CURLOPT_URL, "http://localhost/query.php");
std::string buf("q=");
buf += s;
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, buf.c_str());

关于C++ Curl 后动态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50823704/

相关文章:

php - 为什么 cURL 会进入无限循环?

php - 在 php 中使用 curl 时 move_uploded_file 不起作用

javascript - Node.js express路由POST请求空体,使用body-parser

node.js - reCAPTCHA - 验证用户响应时的错误代码 : 'missing-input-response' , 'missing-input-secret'(缺少 POST 详细信息)

c++ - 将 initialOwner 设置为 TRUE 的 CreateMutex 使创建者进程保持互斥直到完成

c++ - sqlite 准备语句 - 如何调试

ruby-on-rails - 如何在 Ruby 上执行这种 CURL 请求

delphi - Indy 在每个第 72 个字符处添加 = 并使用多部分表单数据发布

c++ - 复制范围的优化

c++ - Factory 类的典型 C++ 实现是否存在缺陷?