将cURL内容结果保存到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 =;

string contents = "";

我想将curl html内容的结果保存在字符串中,我该怎么做?
这是一个愚蠢的问题,但不幸的是,我找不到任何地方的cURL 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!

推荐答案

您必须使用设置写回调。我现在不能测试编译这个,但函数应该看起来接近;

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;
}

然后通过执行

readBuffer.clear();
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
// ...other curl options
res = curl_easy_perform(curl);

调用后, readBuffer 内容。

编辑:您可以使用 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 ++中的字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 23:10