使用 C++ 中的预定义变量发出 cURL GET 请求

Making a cURL GET request using pre-defined variables in C++

本文关键字:cURL GET 请求 变量 C++ 预定义 使用      更新时间:2023-10-16

我目前正在macOS上编写一个C++程序,该程序要求我们从用户那里获取两个变量,即HWID和IP地址,并在这样的get请求中使用它们;

CURL* curl;
string result;
curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_URL, "website.com/c.php?ip=" + ip + "&hwid=" + hwid);

这就是hwidip的定义;

auto hwid = al.exec("ioreg -rd1 -c IOPlatformExpertDevice | awk '/IOPlatformUUID/ { print $3; }'");
auto ip = al.exec("dig +short myip.opendns.com @resolver1.opendns.com.");

请记住,al.exec 只是一个执行并返回终端命令输出的函数。

但是,执行所有这些操作的问题在于,我为参数提供了curl_easy_setopt不正确的类型......我在发出 GET 请求时遇到这些错误,如前所述;

Cannot pass object of non-trivial type 'basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >' through variadic function; call will abort at runtime

任何帮助将不胜感激。

cURL 库是一个 C 库,它的所有函数都是 C 函数。因此,他们不能像std::string那样处理对象。当你这样做"website.com/c.php?ip=" + ip + "&hwid=" + hwid结果是一个std::string的对象。

解决该问题的一种方法是将"website.com/c.php?ip=" + ip + "&hwid=" + hwid的结果保存在变量中,然后将该变量与 c_str 函数一起使用以获取 C 样式字符串:

std::string url = "website.com/c.php?ip=" + ip + "&hwid=" + hwid;
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
<</div> div class="answers">

你应该准备一个const char*来调用curl_easy_setopt()

std::ostringstream oss;
oss << "website.com/c.php?ip=" << ip << "&hwid=" << hwid;
std::string url = oss.str();
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());