CURL框架进行http请求

#include 
#include 
#include 
#include "curl/curl.h"
#include "httpclient.h"
//#pragma comment(lib, "libcurl.lib") 


#define qDebug()   std::cout


httpclient::httpclient()
{
}


httpclient::~httpclient()
{
  curl_global_cleanup();
}



static char error_buffer[CURL_ERROR_SIZE];
static int writer(char*, size_t, size_t, std::string*);
static bool init(CURL*&, const char*, std::string*);


static bool init(CURL*& conn, const char* url, std::string* p_buffer)
{
	CURLcode code;
    curl_slist  *headers=NULL;

	 conn = curl_easy_init();
	if (NULL == conn)
	{
        qDebug()<< " Failed to create CURL connection" ;
        //exit(EXIT_FAILURE);
        return false;
	}

    headers = curl_slist_append(headers, "Content-type:application/json");

    code  =curl_easy_setopt(conn, CURLOPT_HTTPHEADER, headers);
    if (code != CURLE_OK)
    {
         qDebug()<< " Failed to set error buffer " << code;
        return false;
    }

	code = curl_easy_setopt(conn, CURLOPT_ERRORBUFFER, error_buffer);
	if (code != CURLE_OK)
	{
        qDebug()<<" Failed to set error buffer " << code;
		return false;
	}

    curl_easy_setopt(conn, CURLOPT_VERBOSE, 1L);

	code = curl_easy_setopt(conn, CURLOPT_URL, url);
	if (code != CURLE_OK)
	{
        qDebug()<< " Failed to set URL " << error_buffer;
		return false;
	}

	code = curl_easy_setopt(conn, CURLOPT_FOLLOWLOCATION, 1);
	if (code != CURLE_OK)
	{
        qDebug()<<" Failed to set redirect option " << error_buffer;
		return false;
	}

	code = curl_easy_setopt(conn, CURLOPT_WRITEFUNCTION, writer);
	if (code != CURLE_OK)
	{
        qDebug()<< " Failed to set writer " << error_buffer;
		return false;
	}

	code = curl_easy_setopt(conn, CURLOPT_WRITEDATA, p_buffer);
	if (code != CURLE_OK)
	{
        qDebug()<< " Failed to set write data " << error_buffer;
		return false;
	}

	return true;
}

static int writer(char* data, size_t size, size_t nmemb, std::string* writer_data)
{
	unsigned long sizes = size * nmemb;

	if (NULL == writer_data)
	{
		return 0;
	}

	writer_data->append(data, sizes);

	return sizes;
}


int httpclient::http_get(const char* url,const std::string heads[],int len, std::string& buffer, std::string& errinfo)
{
    int ret = 0;
    CURL *conn = NULL;
    CURLcode code;
    curl_global_init(CURL_GLOBAL_DEFAULT);
    buffer.clear();

    curl_slist  *headers=NULL;
     std::string* p_buffer = &buffer;

     conn = curl_easy_init();
    if (NULL == conn)
    {
        qDebug()<< " Failed to create CURL connection" ;
        return -1;
    }

    headers = curl_slist_append(headers, "Content-type:application/json");

    for(int index =0;index

你可能感兴趣的:(QT开发,http,c++,c语言)