将 cURL 内容结果保存到 C++ 中的字符串中

Save cURL content result into a string in C++(将 cURL 内容结果保存到 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, readBuffershould 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++ 中的字符串中

基础教程推荐