#define _CURLPLUS_H__
#include <curl/curl.h>
#endif
#include <curl/easy.h>
#endif
#include <string>
{
class Curlplus
{
public:
static Curlplus& get_instance();
string post(const string& url,const string& content) const;
string get(const string& url) const;
protected:
Curlplus(void);
~Curlplus(void);
Curlplus(const Curlplus&);
Curlplus& operator=(const Curlplus&);
static int writer(char *data, size_t size, size_t nmemb,std::string *writerData);
private:
static auto_ptr<Curlplus> _instance;
inline void _setCurlopt(CURL *curl,const string& url) const;
// default timeout 300s
static const int _defaulttimeout = 300;
static string buffer;
friend class auto_ptr<Curlplus>;
};
}
#include "Curlplus.h"
#endif
using namespace CP;
string Curlplus::buffer;
static char errorBuffer[CURL_ERROR_SIZE];
{
if(_instance.get() == NULL)
{
_instance.reset(new Curlplus());
}
}
{
if (writerData == NULL)
return 0;
int len = size*nmemb;
writerData->append(data, len);
}
{
if(code != CURLE_OK)
{
cout << "curl_init failed, error code is: " << code;
}
}
Curlplus::~Curlplus(void)
{
curl_global_cleanup();
}
{
buffer="";
CURL *curl = curl_easy_init();
if(curl == NULL)
{
cout << "curl_easy_init failed ";
}
curl_easy_setopt(curl, CURLOPT_POST, 1 );
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, content.c_str());
if(code != CURLE_OK)
{
cout << "curl_easy_perform failed: "<< code;
}
curl_easy_cleanup(curl);
}
{
buffer="";
CURL *curl = curl_easy_init();
if(curl == NULL)
{
cout << "curl_easy_init failed ";
}
CURLcode code = curl_easy_perform(curl);
{
cout << "curl_easy_perform failed: "<< code;
}
curl_easy_cleanup(curl);
return buffer;
}
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer);
curl_easy_setopt(curl, CURLOPT_HEADER, 0);
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_TIMEOUT, _defaulttimeout);
//curl_easy_setopt(curl, CURLOPT_VERBOSE, true);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, Curlplus::writer);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
參數:flags
CURL_GLOBAL_ALL Initialize everything possible. This sets all known bits.
curl_easy_init用來初始化一個CURL的指針(有些像返回FILE類型的指針一樣). 相應的在調用結束時要用curl_easy_cleanup函數清理. 一般curl_easy_init意味着一個會話的開始. 它的返回值是CURL *,curl_easy_init函數是線程相關的,也就是說不能在一個線程中調用另外一個線程通過curl_easy_init創建的CURL指針。
3:CURLcode curl_easy_setopt(CURL *handle, CURLoption option, parameter);
描述: 這個函數最重要了.幾乎所有的curl 程序都要頻繁的使用它.它告訴curl庫.程序將有如何的行爲. 比如要查看一個網頁的html代碼等.,要想具體瞭解CURL的行爲,必須對CURLoption有足夠的瞭解,具體可以參考