如何解决将变量传递给 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 << '\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,CURLOPT_CUSTOMREQUEST,"POST");
curl_easy_setopt(bnd,CURLOPT_FTP_SKIP_PASV_IP,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 请求中发送一些奇怪的十六进制东西 V\x1b{
。
我尝试添加 line.c_str()
但这不起作用。它在对数据进行硬编码时有效。
解决方法
std::string line
不能传递给 C API 函数。像使用 line.c_str()
一样使用 agent_name
。
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());
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。