将变量传递给CURLOPT_POSTFIELDS c++

2022-05-17 00:00:00 variables libcurl c++

我正在尝试将变量传递给CURLOPT_POSTFIELDS。我的当前代码:

size_t curl_write( void *ptr, size_t size, size_t nmemb, void *stream)
{
  std::string cmd(static_cast<char*>(ptr), size * nmemb);
  redi::ipstream proc(cmd.c_str(), redi::pstreams::pstdout | redi::pstreams::pstderr);

  std::string line;
  while (std::getline(proc.out(), line))
    std::cout << line << '
';

  CURLcode sendb;
  CURL *bnd;

  bnd = curl_easy_init();
  curl_easy_setopt(bnd, CURLOPT_BUFFERSIZE, 102400L);
  curl_easy_setopt(bnd, CURLOPT_URL, agent_name.c_str());
  curl_easy_setopt(bnd, CURLOPT_NOPROGRESS, 1L);
  curl_easy_setopt(bnd, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)line.size());
  curl_easy_setopt(bnd, CURLOPT_POSTFIELDS, line.c_str());
  curl_easy_setopt(bnd, CURLOPT_SSL_VERIFYPEER, 0L);
  curl_easy_setopt(bnd, CURLOPT_SSL_VERIFYHOST, 0L);
  curl_easy_setopt(bnd, CURLOPT_CUSTOMREQUEST, "POST");
  curl_easy_setopt(bnd, CURLOPT_FTP_SKIP_PASV_IP, 1L);
  curl_easy_setopt(bnd, CURLOPT_TCP_KEEPALIVE, 1L);
  

  sendb = curl_easy_perform(bnd);

  std::cout << sendb;

  curl_easy_cleanup(bnd);
  bnd = NULL;

  if (proc.eof() && proc.fail())
    proc.clear();
}

这会在POST请求中发送一些奇怪的十六进制内容Vx1b{

我已尝试添加line.c_str(),但不起作用。它在对数据进行硬编码时起作用。


解决方案

std::string line无法传递给C API函数。像使用agent_name一样使用line.c_str()

curl_easy_setopt(bnd, CURLOPT_POSTFIELDS, line.c_str());

另外,最好是传递字符串长度,而不是魔术常量4,或者不要设置以0结尾的字符串的长度。

// Unnecessary for 0-terminated string.
curl_easy_setopt(bnd, CURLOPT_COPYPOSTFIELDS, line.c_str());

相关文章