libcurl不会加载URL的内容

问题描述 投票:0回答:1

我正在尝试加载此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实际上会在访问时发送短信。在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
}
c++ curl libcurl
1个回答
1
投票

这条线错了:

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()的返回值执行任何错误检查。所以,你的代码可能在任何一个地方失败,你永远不会知道它。

© www.soinside.com 2019 - 2024. All rights reserved.