C libcurl get output into a string

前端 未结 4 1156
粉色の甜心
粉色の甜心 2020-11-28 18:36

I want to store the result of this curl function in a variable, how can I do so?

#include 
#include 

int main(void)
{
  CU         


        
4条回答
  •  醉酒成梦
    2020-11-28 19:29

    Here's a C++ flavor of the accepted answer from alex-jasmin

    #include 
    #include 
    #include 
    
    size_t writefunc(void *ptr, size_t size, size_t nmemb, std::string *s) 
    {
      s->append(static_cast(ptr), size*nmemb);
      return size*nmemb;
    }
    
    int main(void)
    {
      CURL *curl = curl_easy_init();
      if (curl)
      {
        std::string s;
    
        curl_easy_setopt(curl, CURLOPT_URL, "curl.haxx.se");
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);
    
        CURLcode res = curl_easy_perform(curl);
    
        std::cout << s << std::endl;
    
        /* always cleanup */
        curl_easy_cleanup(curl);
      }
      return 0;
    }
    
    

提交回复
热议问题