問題描述
int main(void)
{
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://www.google.com");
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
_getch();
return 0;
}
string contents = "";
我想將 curl html 內容的結果保存在一個字符串中,我該怎么做?這是一個愚蠢的問題,但不幸的是,我在 C++ 的 cURL 示例中找不到任何地方謝謝!
I would like to save the result of the curl html content in a string, how do I do this? It's a silly question but unfortunately, I couldn't find anywhere in the cURL examples for C++ thanks!
推薦答案
你將不得不使用 CURLOPT_WRITEFUNCTION
設置寫入回調.我現在無法測試編譯這個,但函數應該看起來很接近;
You will have to use CURLOPT_WRITEFUNCTION
to set a callback for writing. I can't test to compile this right now, but the function should look something close to;
static std::string readBuffer;
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
size_t realsize = size * nmemb;
readBuffer.append(contents, realsize);
return realsize;
}
然后通過doing調用它;
Then call it by doing;
readBuffer.clear();
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
// ...other curl options
res = curl_easy_perform(curl);
調用后,readBuffer
應該有你的內容.
After the call, readBuffer
should have your contents.
您可以使用 CURLOPT_WRITEDATA
來傳遞緩沖區字符串,而不是將其設為靜態.在這種情況下,為了簡單起見,我只是將其設為靜態.一個很好看的頁面(除了上面鏈接的例子)是這里的解釋的選項.
You can use CURLOPT_WRITEDATA
to pass the buffer string instead of making it static. In this case I just made it static for simplicity. A good page to look (besides the linked example above) is here for an explanation of the options.
Edit2:根據要求,這是一個沒有靜態字符串緩沖區的完整工作示例;
As requested, here's a complete working example without the static string buffer;
#include <iostream>
#include <string>
#include <curl/curl.h>
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
int main(void)
{
CURL *curl;
CURLcode res;
std::string readBuffer;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://www.google.com");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
std::cout << readBuffer << std::endl;
}
return 0;
}
這篇關于將 cURL 內容結果保存到 C++ 中的字符串中的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!