将变量传递给CURLOPT_POSTFIELDS c++ [英] passing variables into CURLOPT_POSTFIELDS c++

查看:62
本文介绍了将变量传递给CURLOPT_POSTFIELDS 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());

这篇关于将变量传递给CURLOPT_POSTFIELDS c++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆