user15386494
user15386494

Reputation:

passing variables into CURLOPT_POSTFIELDS c++

I am trying to pass a variable into CURLOPT_POSTFIELDS. My current code:

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 << '\n';

  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();
}

This sends some weird hex thing V\x1b{ in the POST request.

I've tried adding line.c_str() but that does not work. It works when hard-coding the data.

Upvotes: 0

Views: 414

Answers (1)

3CxEZiVlQ
3CxEZiVlQ

Reputation: 38773

std::string line can't be passed to a C API function. Use line.c_str() like you did for agent_name.

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

Also it is better to pass the string length rather than a magic constant 4 or not to set the length of 0-terminated string.

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

Upvotes: 1

Related Questions