c++ - libcurl 不会加载 URL 的内容

标签 c++ curl libcurl

我正在尝试加载此 URL 的内容以发送短信;

https://app2.simpletexting.com/v1/send?token=[api key]&phone=[phone number]&message=Weather%20Alert!

使用这段代码实现 libcurl:

std::string sendSMS(std::string smsMessage, std::string usrID) {   
    std::string simplePath = "debugOld/libDoc.txt";
    std::string preSmsURL = "https://app2.simpletexting.com/v1/send?token=";

    std::cout << "\n" << getFile(simplePath) << "\n";
    std::string fullSmsURL = preSmsURL + getFile(simplePath) + "&phone=" + usrID + "&message=" + smsMessage;

    std::cout << fullSmsURL;

    //Outputs URL contents into a file
    CURL *curl;
    FILE *fd;
    CURLcode res;
    char newFile[FILENAME_MAX] = "debugOld/noSuccess.md";
    curl = curl_easy_init();
    if (curl) {
        fd = fopen(newFile, "wb");
        curl_easy_setopt(curl, CURLOPT_URL, fullSmsURL);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fd);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        fclose(fd);
    }
}

我以前几乎使用过这段代码将 URL 的 JSON 内容保存到文件中,尽管我在这里尝试了一些不同的东西。

访问此 URL 时实际上会发送 SMS。在 cli 中使用 curl 时,这样做没有问题。虽然来自 C++,但它不会将任何内容视为错误,只是发送短信的实际功能可能没有以与我实际访问 URL 时相同的方式启动。

我在谷歌上搜索了某种解决方案,但无济于事。也许我太新手了,无法准确地知道要搜索什么。

编辑 #1:getFile 函数

//Read given file
std::string getFile(std::string path) {
    std::string nLine;
    std::ifstream file_(path);

    if (file_.is_open()) {
        while (getline(file_, nLine)) {
            return nLine;
        }
        file_.close();
    }
    else {
        std::cout << "file is not open" << "\n";
        return "Error 0x000001: inaccesable file location";
    }
    return "Unknown error in function 'getFile()'"; //This should never happen
}

最佳答案

这一行是错误的:

curl_easy_setopt(curl, CURLOPT_URL, fullSmsURL);

CURLOPT_URL 需要一个 char* 指针指向以 null 结尾的 C 字符串,而不是 std::string 对象。您需要改用它:

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

此外,您没有对 getFile()fopen()curl_easy_perform() 的返回值执行任何错误检查根本。因此,您的代码可能在其中任何一个地方失败,而您永远不会知道。

关于c++ - libcurl 不会加载 URL 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55014741/

相关文章:

C++ 内部类不编译

c++ - 最快的语音识别库 C++

c++ - 超时后检查服务器是否收到数据

c++ - 使用 libcurl 而不安装它

laravel - PayPal 沙盒上的 cURL 56 错误

python - 使用 pycurl 发布文件并传递参数

c++ - 我应该如何将此 std::array<> 传递给函数?

c++ - Clang 可以输出 double 转换为 float 的警告吗?

javascript - 在 javascript 中执行 curl 请求?

php - CURLOPT_PUT 与 CURLOPT_POSTFIELDS