Using LIBCurl with C++ Simple OOP Static Class Example

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

Tags: ,

Leave a Reply

Post Categories

Ready Made Templates

Template 27975Template 27976Template 27934Template 27949Template 28042Template 28043Template 28045Template 28011Template 27970

About ProjectiveMotion

We develop cost effective websites for small to mid size businesses. Our passion is customer service and a job well done. We make use of all tools available in order to provide the product to fit your needs.

Do you have a business? Do you have a website? Don't know how to get started? We answer all inquiries within 12 hours. Our products have 30 day free client support.