Save cURL content result into a string in C++

前端 未结 7 1872
鱼传尺愫
鱼传尺愫 2020-11-30 22:16
int main(void)
{
  CURL *curl;
  CURLcode res;

  curl = curl_easy_init();
  if(curl) {
    curl_easy_setopt(curl, CURLOPT_URL, \"http://www.google.com\");
    curl_         


        
7条回答
  •  自闭症患者
    2020-11-30 23:12

    Using the 'new' C++11 lambda functionality, this can be done in a few lines of code.

    #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(
        [](char* ptr, size_t size, size_t nmemb, void* resultBody){
            *(static_cast(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
    

    Note the __stdcall cast is needed to comply to the C calling convention (cURL is a C library)

提交回复
热议问题