【发布时间】:2019-03-06 02:44:31
【问题描述】:
我正在尝试加载此 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 的方式不同。
我在谷歌上搜索了某种解决方案,但无济于事。也许我太新手了,无法 curl 确切地知道要搜索什么。
编辑 #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
}
【问题讨论】:
-
您是否检查过
getFile返回的任何流氓字符(例如换行符)?也许显示该功能的实现。 -
我已经使用 getFile 函数编辑了帖子。我看不到任何东西会在 getFile() 中导致它,尽管我现在不相信自己。谢谢!
-
尝试输出它返回的字符串的长度,并检查它是否与您期望的字符数匹配。
-
只看你对 CURL 的调用(我没有使用经验),我不禁注意到它接受 C 风格接口中的任意参数,所以如果你传递 @ 987654325@ 给它(这是一个
std::string),事情可能真的出错了。std::string不会将自身隐式转换为const char*。试试这个:curl_easy_setopt(curl, CURLOPT_URL, fullSmsURL.c_str()); -
这似乎也是正确的。读取文件时,它得到 32 个字符,相当于字符串长度。以防我的计数错误,字符串(类似于):1jb1d0c0632d40e6hc758b06b5c5f9af