#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <sstream>
#include <string.h>
#include <curl/curl.h>

using namespace std;

// Copied this function from haxx.se
static int writer(char *data, size_t size, size_t nmemb, std::string 
*buffer)
{
	// What we will return
	int result = 0;

	// Is there anything in the buffer?
	if (buffer != NULL)
	{
		// Append the data to the buffer
		buffer->append(data, size * nmemb);

		// How much did we write?
		result = size * nmemb;
	}

	return result;
}

static bool http_call (void) {
	CURL *curl;

	curl = curl_easy_init();
	if(curl) {
		// URL übergeben
		curl_easy_setopt(curl, CURLOPT_URL, "http://www.example.com/");

		// Keine Kopfzeile einblenden
		curl_easy_setopt(curl, CURLOPT_HEADER, false);

		// Verbindung danach beenden
		curl_easy_setopt(curl, CURLOPT_FORBID_REUSE, true);

		// Pufferoptionen
		char errorBuffer[CURL_ERROR_SIZE];
		curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer);
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer);
		string buffer;
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);

		// Benutzerdefinierter User-Agent-Name
		curl_easy_setopt(curl, CURLOPT_USERAGENT, "Hello World Browser");

		// Einen Timeout setzen
		curl_easy_setopt(curl, CURLOPT_TIMEOUT, 1);

		// Weiterleitungen beachten, aber nur max. 50x
		curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, true);
		curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 50);

		// Einen HTTP-Fehler-Statuscode beachten
		curl_easy_setopt(curl, CURLOPT_FAILONERROR, true);

		// SSL-Zertifikate nicht prüfen (Warnung! Sicherheitslücke)
		// http://ademar.name/blog/2006/04/curl-ssl-certificate-problem-v.html
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);

		// Abfrage ausführen und Resultat speichern
		CURLcode res;
		res = curl_easy_perform(curl);

		// Clean up
		curl_easy_cleanup(curl);

		// Alles OK?
		if (res == CURLE_OK)
		{

			return true;
		}
		else
		{
			return false;
		}
	} else return false;
}

int main(void) {
        while (true) {
                cout << "A" << ::std::endl;
                http_call();
                sleep(2);
        }
        return 0;
}
