您必须使用CURLOPT_WRITEFUNCTION 设置回调以进行写入。我现在无法测试编译它,但函数看起来应该很接近;
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调用它;
readBuffer.clear();
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
// ...other curl options
res = curl_easy_perform(curl);
通话结束后,readBuffer应该有你的内容了。
编辑:您可以使用CURLOPT_WRITEDATA 传递缓冲区字符串,而不是使其成为静态。在这种情况下,为了简单起见,我只是将其设为静态。一个不错的页面(除了上面的链接示例)是here,用于解释选项。
Edit2:根据要求,这是一个没有静态字符串缓冲区的完整工作示例;
#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;
}