Save cURL content result into a string in C++(将 cURL 内容结果保存到 C++ 中的字符串中)
问题描述
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++ 中的字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 cURL 内容结果保存到 C++ 中的字符串中
基础教程推荐
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01