【问题标题】:C++ Curl post dynamic varC++ Curl post动态变量
【发布时间】:2018-11-22 05:41:38
【问题描述】:

我想在 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);
                                                    ~~~~~^~~

【问题讨论】:

    标签: c++ curl post


    【解决方案1】:

    您必须自己连接"q="s,Cpp 中没有将字符数组与指向字符的指针连接起来的运算符+。用"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());
    

    【讨论】:

    • 请注意,buf 必须在内存中保持有效且未经修改,直到使用传递给 CURLOPT_POSTFIELDSchar* 指针完成 curl_easy_perform()。否则,您必须改用CURLOPT_COPYPOSTFIELDS
    • 谢谢@rafix07 !!
    猜你喜欢
    • 2013-10-23
    • 2014-09-12
    • 2018-02-16
    • 2017-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多