在C++中将cURL内容结果保存为字符串

9bfwbjaz  于 2023-08-09  发布在  其他
关注(0)|答案(8)|浏览(143)
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示例中找不到任何地方,谢谢!

7uhlpewt

7uhlpewt1#

您必须使用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;
}

字符串
然后通过做来调用它;

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


调用后,readBuffer应该有您的内容。
编辑:您可以使用CURLOPT_WRITEDATA来传递缓冲区字符串,而不是使其成为静态的。在本例中,为了简单起见,我将其设置为静态。here是一个很好的页面(除了上面的链接示例),它解释了这些选项。
Edit 2:按照要求,这里有一个没有静态字符串缓冲区的完整工作示例;

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

s8vozzvw

s8vozzvw2#

在我的博客上,我有一个简单的 Package 器类published来执行这个任务。
使用示例:

#include "HTTPDownloader.hpp"

int main(int argc, char** argv) {
    HTTPDownloader downloader;
    std::string content = downloader.download("https://stackoverflow.com");
    std::cout << content << std::endl;
}

字符串
下面是头文件:

/**
 * HTTPDownloader.hpp
 *
 * A simple C++ wrapper for the libcurl easy API.
 *
 * Written by Uli Köhler (techoverflow.net)
 * Published under CC0 1.0 Universal (public domain)
 */
#ifndef HTTPDOWNLOADER_HPP
#define HTTPDOWNLOADER_HPP

#include <string>

/**
 * A non-threadsafe simple libcURL-easy based HTTP downloader
 */
class HTTPDownloader {
public:
    HTTPDownloader();
    ~HTTPDownloader();
    /**
     * Download a file using HTTP GET and store in in a std::string
     * @param url The URL to download
     * @return The download result
     */
    std::string download(const std::string& url);
private:
    void* curl;
};

#endif  /* HTTPDOWNLOADER_HPP */


下面是源代码:

/**
 * HTTPDownloader.cpp
 *
 * A simple C++ wrapper for the libcurl easy API.
 *
 * Written by Uli Köhler (techoverflow.net)
 * Published under CC0 1.0 Universal (public domain)
 */
#include "HTTPDownloader.hpp"
#include <curl/curl.h>
#include <curl/easy.h>
#include <curl/curlbuild.h>
#include <sstream>
#include <iostream>
using namespace std;

size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream) {
    string data((const char*) ptr, (size_t) size * nmemb);
    *((stringstream*) stream) << data;
    return size * nmemb;
}

HTTPDownloader::HTTPDownloader() {
    curl = curl_easy_init();
}

HTTPDownloader::~HTTPDownloader() {
    curl_easy_cleanup(curl);
}

string HTTPDownloader::download(const std::string& url) {
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
    /* example.com is redirected, so we tell libcurl to follow redirection */
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
    curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); //Prevent "longjmp causes uninitialized stack frame" bug
    curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, "deflate");
    std::stringstream out;
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &out);
    /* Perform the request, res will get the return code */
    CURLcode res = curl_easy_perform(curl);
    /* Check for errors */
    if (res != CURLE_OK) {
        fprintf(stderr, "curl_easy_perform() failed: %s\n",
                curl_easy_strerror(res));
    }
    return out.str();
}

polkgigr

polkgigr3#

使用“新”的C++11 lambda功能,这可以在几行代码中完成。

#ifndef WIN32 #define __stdcall "" #endif //For compatibility with both Linux and Windows
std::string resultBody { };
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &resultBody);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, static_cast<size_t (__stdcall *)(char*, size_t, size_t, void*)>(
    [](char* ptr, size_t size, size_t nmemb, void* resultBody){
        *(static_cast<std::string*>(resultBody)) += std::string {ptr, size * nmemb};
        return size * nmemb;
    }
));

CURLcode curlResult = curl_easy_perform(curl);
std::cout << "RESULT BODY:\n" << resultBody << std::endl;
// Cleanup etc

字符串
注意,需要使用__stdcall强制转换来遵守C调用约定(cURL是一个C库)

lmyy7pcs

lmyy7pcs4#

这可能不会立即起作用,但应该给予你一个想法:

#include <string>
#include <curl.h>
#include <stdio.h>
size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
    size_t written;
    written = fwrite(ptr, size, nmemb, stream);
    return written;
}

int main() {
    std::string tempname = "temp";
    CURL *curl;
    CURLcode res;
    curl = curl_easy_init();
    if(curl) {
      FILE *fp = fopen(tempname.c_str(),"wb");
      curl_easy_setopt(curl, CURLOPT_URL, "http://www.google.com");
      curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); 
      curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
      res = curl_easy_perform(curl);
      curl_easy_cleanup(curl);
      fclose(fp);
      fp = fopen(tempname.c_str(),"rb");
      fseek (fp , 0 , SEEK_END);
      long lSize = ftell (fp);
      rewind(fp);
      char *buffer = new char[lSize+1];
      fread (buffer, 1, lSize, fp);
      buffer[lSize] = 0;
      fclose(fp);
      std::string content(buffer);
      delete [] buffer;
    }
}

字符串

t0ybt7op

t0ybt7op5#

给出了一个有用但简单的解决方案,它重载了std::ostream::operator<<

#include <ostream>

#include <curl/curl.h>

size_t curlCbToStream (
    char * buffer,
    size_t nitems,
    size_t size,
    std::ostream * sout
)
{
    *sout << buffer;

    return nitems * size;
}

std::ostream & operator<< (
    std::ostream & sout,
    CURL * request
)
{
    ::curl_easy_setopt(request, CURLOPT_WRITEDATA, & sout);
    ::curl_easy_setopt(request, CURLOPT_WRITEFUNCTION, curlCbToStream);
    ::curl_easy_perform(request);

    return sout;
}

字符串
所采用方法的可能缺点可能是:

typedef void CURL;


这意味着它涵盖了所有已知的指针类型。

nhaq1z21

nhaq1z216#

基于@JoachimIsaksson的回答,这里是一个更详细的输出,它处理内存不足,并对curl的最大输出有限制(因为CURLOPT_MAXFILESIZE仅基于头信息而不是传输的实际大小)。

#DEFINE MAX_FILE_SIZE = 10485760 //10 MiB

size_t curl_to_string(void *ptr, size_t size, size_t count, void *stream)
{
    if(((string*)stream)->size() + (size * count) > MAX_FILE_SIZE)
    {
        cerr<<endl<<"Could not allocate curl to string, output size (current_size:"<<((string*)stream)->size()<<"bytes + buffer:"<<(size * count) << "bytes) would exceed the MAX_FILE_SIZE ("<<MAX_FILE_SIZE<<"bytes)";
        return 0;
    }
    int retry=0;
    while(true)
    {
        try{
            ((string*)stream)->append((char*)ptr, 0, size*count);
            break;// successful
        }catch (const std::bad_alloc&) {
            retry++;
            if(retry>100)
            {
                cerr<<endl<<"Could not allocate curl to string, probably not enough memory, aborting after : "<<retry<<" tries at 10s apart";
                return 0;
            }
            cerr<<endl<<"Could not allocate curl to string, probably not enough memory, sleeping 10s, try:"<<retry;
            sleep(10);
        }
    }
  return size*count;
}

字符串

hjzp0vay

hjzp0vay7#

我将Joachim Isaksson的答案与CURLOPT_WRITEFUNCTION的现代C++适配一起使用。
没有C风格强制转换的编译器的唠叨。

static auto WriteCallback(char* ptr, size_t size, size_t nmemb, void* userdata) -> size_t {
  static_cast<string*>(userdata)->append(ptr, size * nmemb);
  return size * nmemb;
}

字符串

o2gm4chl

o2gm4chl8#

这里有一个完整的例子,如何使用curl将网站的内容放入C++中的std::string。
编译时不要忘记标志-lcurl。

/**
 * 
*/

////////////////////////////////////////////////////////////////////////////////
// Includes - default libraries - C++
////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <string>
#include <sstream> // for ostringstream
#include <memory>

////////////////////////////////////////////////////////////////////////////////
// Includes - others libraries - C++
////////////////////////////////////////////////////////////////////////////////
#include <curl/curl.h>

////////////////////////////////////////////////////////////////////////////////
// show function
////////////////////////////////////////////////////////////////////////////////
std::string
args_to_str(const std::ostringstream& os)
{
  return os.str();
}

template<typename T, typename ... Args>
std::string
args_to_str(std::ostringstream& os, const T val, const Args ... args) 
{
  os << val;
  return args_to_str(os, args ...);
}

template<typename ... Args>
void 
show(const Args ... args) 
{  
    std::ostringstream os;  
    std::cout << args_to_str(os, args ...);
}


////////////////////////////////////////////////////////////////////////////////
// headers
////////////////////////////////////////////////////////////////////////////////
template<typename ... Args>
void error(const Args ... args);

size_t curl_to_string(void *ptr, size_t size, size_t nmemb, void *data);

std::string get_content_from_website(CURL* curl, const std::string& url);

void curl_free(CURL *curl);

////////////////////////////////////////////////////////////////////////////////
// main
////////////////////////////////////////////////////////////////////////////////
int
main()
{
    ////////////////////////////////////////////////////////////////////////////////
    // init libcurl
    ////////////////////////////////////////////////////////////////////////////////
    std::shared_ptr<CURL> curl (curl_easy_init(), curl_free);
    if(!curl.get()) error("cannot initialize CURL.");
    curl_easy_setopt(curl.get(), CURLOPT_VERBOSE, 1L);

    ////////////////////////////////////////////////////////////////////////////////
    // site that will be fetched
    ////////////////////////////////////////////////////////////////////////////////
    const std::string url = "https://www.fundsexplorer.com.br/funds/knsc11"; // put your website here

    ////////////////////////////////////////////////////////////////////////////////
    // fetch the content of the site
    ////////////////////////////////////////////////////////////////////////////////
    const std::string site = get_content_from_website(curl.get(), url);

    ////////////////////////////////////////////////////////////////////////////////
    // print the result
    ////////////////////////////////////////////////////////////////////////////////
    show(site);

    return 0;
}

////////////////////////////////////////////////////////////////////////////////
// functions
////////////////////////////////////////////////////////////////////////////////
template<typename ... Args>
void 
error(const Args ... args)
{  
    show(args ...);  
    abort();
}

std::string 
get_content_from_website(CURL* curl, const std::string& url)
{ 
    CURLcode res;
    res = curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
    if(res != CURLE_OK) error("Cannot set curl url.\n");

    res = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_to_string);
    if(res != CURLE_OK) error("Cannot copy the C_STR to C++ string.\n");

    std::string result;
    res = curl_easy_setopt(curl, CURLOPT_WRITEDATA, &result);
    if(res != CURLE_OK) error("Cannot set the curl write data.\n");

    res = curl_easy_perform(curl);
    if(res != CURLE_OK) error("Cannot perform curl.\n");

    return result;
}

size_t curl_to_string(void *ptr, size_t size, size_t nmemb, void *data)
{
    std::string* str = static_cast<std::string*>(data);
    char* sptr = static_cast<char*>(ptr);
    size_t total = size * nmemb;
    const auto str_old_size = (*str).size();
    (*str).resize(str_old_size + total);

    
    for(size_t x = 0; x < total; ++x)
    {
        (*str)[str_old_size + x] = sptr[x];
    }

    return total;
}

void 
curl_free(CURL *curl)
{
  curl_easy_cleanup(curl);
  curl = NULL;
  curl_global_cleanup();
}

字符串

相关问题