组合字符串不适用于 libCurl,C++

Combined string isn't working for libCurl in C++

本文关键字:C++ libCurl 适用于 字符串 不适用 组合      更新时间:2023-10-16

基本上,我现在使用的程序/代码是从PHP脚本返回消息。我遇到的问题是,当我为 URL 提供组合字符串时,它不会返回任何内容。但是当我手动输入它时,它会返回正确的信息。这是我在下面使用的代码:

std::string Login(std::string uname, std::string pass)
{
CURL* curl;
CURLcode res;
std::string readBuffer;
std::string path = "localhost/files/login.php?username=" + uname + "&password=" + pass;
std::cout << uname << "  " << pass;
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, "localhost/files/login.php?username=123&password=123");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
return readBuffer;
}
return "Failed";
}

这种方式之所以有效,是因为我手动输入了URL,但是当我这样做时,它不会返回任何内容:

std::string path = "localhost/files/login.php?username=" + uname + "&password=" + pass;
curl_easy_setopt(curl, CURLOPT_URL, path);

我不确定我是否使用了错误的变量或其他变量。我是使用PHP和libCurl以及任何与网络相关的事物的新手。

CURLOPT_URL期望以 C 样式的 null 结尾的char*字符串指针作为输入,而不是std::string。 您可以使用std::string::c_str()方法从std::string获取兼容的const char*指针:

curl_easy_setopt(curl, CURLOPT_URL, path.c_str());