Using LIBCurl with C++ Simple OOP Static Class ExampleUsando LIBCurl en C++ Ejemplo de OOP

This is a quick class in C++ that I slapped together from an example I found at http://www.luckyspin.org/?p=28.

I’ve been writing a php bot using curl for one of my favorite online games and I decided to make it public. This would be one of my latest public releases in a while. It turned out that PHP is not the best language to use due to poor portability. I played around with bambalam (PHP ‘compiler’) and also WinBinder, but both packages are severely outdated. All my code was written in PHP5, and bambalam only supports php 4. So, Now I’m going back to hardcore programming and coming up with a solution soon. I’ve already got libcurl, and boost hooked up and ready to go!

#include <iostream>
#include "curl/curl.h"

class MyCurl
{
private:

public:
// Write any errors in here

static int writer(char *data, size_t size, size_t nmemb, std::string *buffer_in)
{

// Is there anything in the buffer?
if (buffer_in != NULL)
{
// Append the data to the buffer
buffer_in->append(data, size * nmemb);

// How much did we write?
return size * nmemb;
}

return 0;
}

static std::string get(const char* url)
{
CURL *curl;
CURLcode result;

// Create our curl handle
curl = curl_easy_init();

char errorBuffer[CURL_ERROR_SIZE];
// Write all expected data in here
std::string buffer;

if (curl)
{
// Now set up all of the curl options
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer);
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_HEADER, 0);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(curl, CURLOPT_COOKIEJAR, "cookies.txt");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, MyCurl::writer);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);

// Attempt to retrieve the remote page
result = curl_easy_perform(curl);

// Always cleanup
curl_easy_cleanup(curl);
}

if(result == CURLE_OK)
return buffer;
return std::string();
}
};


  • harry

    Hi, can I ask what exactly is returned in buffer? Is it by any chance what the posted to page responded?

    • Yes, It returns the page body in a string or an empty string if an error ocurred. Just call MyCurl::get(“http://…”);

  • David Vargas

    Thanks a lot this post was helpful for me, I’m getting started with c and It was just what I was looking for !!!

  • ferdinand

    Hi Amado,
    is it possible with curl to filter the url content.
    for example – what if i only want the content of a url – what i mean is only the content between the body-html-tag?

    .
    .
    only this content here
    .
    .


    and …
    is it possible to remove all html-tags?
    Thank you in advance
    ferdinand