基于libcurl的restfull接口 post posts get gets

头文件

#pragma once



#ifndef __HTTP_CURL_H__
#define __HTTP_CURL_H__

#include <string>
#include "curl.h"
#include "MqBase.h"
#include "Config.h"
class CHttpClient:public MqBase
{
public:
    CHttpClient(void);
    ~CHttpClient(void);

public:
    /**
    * @brief HTTP POST请求
    * @param strUrl 输入参数,请求的Url地址,如:http://www.baidu.com
    * @param strPost 输入参数,使用如下格式para1=val1¶2=val2&…
    * @param strResponse 输出参数,返回的内容
    * @return 返回是否Post成功
    */
    int Post(const std::string & strUrl, const std::string & strPost, std::string & strResponse);

    /**
    * @brief HTTP GET请求
    * @param strUrl 输入参数,请求的Url地址,如:http://www.baidu.com
    * @param strResponse 输出参数,返回的内容
    * @return 返回是否Post成功
    */
    int Get(const std::string & strUrl, std::string & strResponse);

    /**
    * @brief HTTPS POST请求,无证书版本
    * @param strUrl 输入参数,请求的Url地址,如:https://www.alipay.com
    * @param strPost 输入参数,使用如下格式para1=val1¶2=val2&…
    * @param strResponse 输出参数,返回的内容
    * @param pCaPath 输入参数,为CA证书的路径.如果输入为NULL,则不验证服务器端证书的有效性.
    * @return 返回是否Post成功
    */
    int Posts(const std::string & strUrl, const std::string & strPost, std::string & strResponse, const char * pCaPath = NULL);

    /**
    * @brief HTTPS GET请求,无证书版本
    * @param strUrl 输入参数,请求的Url地址,如:https://www.alipay.com
    * @param strResponse 输出参数,返回的内容
    * @param pCaPath 输入参数,为CA证书的路径.如果输入为NULL,则不验证服务器端证书的有效性.
    * @return 返回是否Post成功
    */
    int Gets(const std::string & strUrl, std::string & strResponse, const char * pCaPath = NULL);



    HPR_INT32    Init();
    HPR_VOID    Fini();
    HPR_INT32    Connect();
    HPR_VOID    DoPublishAlarm();
    HPR_VOID    CheckMqStatus();
    HPR_INT32    CheckServerStatus( HPR_LONG lTimeOut);
    HPR_VOID    PushMq(char* chMqInfo);
    char*        PopMq();
    HPR_VOID    ClearMqList();
    HPR_INT32    AddToMqSendQueue(string strMsg);
public:
    void SetDebug(bool bDebug);

private:
    bool m_bDebug;
    HPR_HANDLE     m_hLoopPublishMq;
    HPR_BOOL     m_bExit;
    list<char*>    m_listRabbitMq;
};

#endif

源文件

#include "HttpClientCurl.h"
#include "curl.h"
static HPR_VOIDPTR CALLBACK DoPublishAlarmThread(HPR_VOIDPTR param)
{
    CHttpClient *p=(CHttpClient*)param;
    if (p==NULL)
    {
        FIRE_ERROR("input para is NULL");
        return NULL;
    }
    p->DoPublishAlarm();
    return NULL;
}
CHttpClient::CHttpClient(void) : 
m_bDebug(false)
{

}

CHttpClient::~CHttpClient(void)
{

}

static int OnDebug(CURL *, curl_infotype itype, char * pData, size_t size, void *)
{
    if(itype == CURLINFO_TEXT)
    {
        //printf("[TEXT]%s\n", pData);
    }
    else if(itype == CURLINFO_HEADER_IN)
    {
        printf("[HEADER_IN]%s\n", pData);
    }
    else if(itype == CURLINFO_HEADER_OUT)
    {
        printf("[HEADER_OUT]%s\n", pData);
    }
    else if(itype == CURLINFO_DATA_IN)
    {
        printf("[DATA_IN]%s\n", pData);
    }
    else if(itype == CURLINFO_DATA_OUT)
    {
        printf("[DATA_OUT]%s\n", pData);
    }
    return 0;
}

static size_t OnWriteData(void* buffer, size_t size, size_t nmemb, void* lpVoid)
{
    std::string* str = dynamic_cast<std::string*>((std::string *)lpVoid);
    if( NULL == str || NULL == buffer )
    {
        return -1;
    }

    char* pData = (char*)buffer;
    str->append(pData, size * nmemb);
    return nmemb;
}

int CHttpClient::Post(const std::string & strUrl, const std::string & strPost, std::string & strResponse)
{
    CURLcode res;
    CURL* curl = curl_easy_init();
    if(NULL == curl)
    {
        return CURLE_FAILED_INIT;
    }
    if(m_bDebug)
    {
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
        curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, OnDebug);
    }
    curl_easy_setopt(curl, CURLOPT_URL, strUrl.c_str());
    curl_easy_setopt(curl, CURLOPT_POST, 1);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, strPost.c_str());
    curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, OnWriteData);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&strResponse);
    curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
    curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 3);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 3);
    res = curl_easy_perform(curl);
    curl_easy_cleanup(curl);
    return res;
}

int CHttpClient::Get(const std::string & strUrl, std::string & strResponse)
{
    CURLcode res;
    CURL* curl = curl_easy_init();
    if(NULL == curl)
    {
        return CURLE_FAILED_INIT;
    }
    if(m_bDebug)
    {
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
        curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, OnDebug);
    }
    curl_easy_setopt(curl, CURLOPT_URL, strUrl.c_str());
    curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, OnWriteData);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&strResponse);
    /**
    * 当多个线程都使用超时处理的时候,同时主线程中有sleep或是wait等操作。
    * 如果不设置这个选项,libcurl将会发信号打断这个wait从而导致程序退出。
    */
    curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
    curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 3);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 3);
    res = curl_easy_perform(curl);
    curl_easy_cleanup(curl);
    return res;
}

int CHttpClient::Posts(const std::string & strUrl, const std::string & strPost, std::string & strResponse, const char * pCaPath)
{
    CURLcode res;
    CURL* curl = curl_easy_init();
    if(NULL == curl)
    {
        return CURLE_FAILED_INIT;
    }
    if(m_bDebug)
    {
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
        curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, OnDebug);
    }
    curl_easy_setopt(curl, CURLOPT_URL, strUrl.c_str());
    curl_easy_setopt(curl, CURLOPT_POST, 1);
    if (strPost!="")
    {
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, strPost.c_str());
        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, strPost.size());
    }
    //curl_easy_setopt(curl, CURLOPT_, headerlist);

    curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, OnWriteData);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&strResponse);
    curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
    if(NULL == pCaPath)
    {
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);
    }
    else
    {
        //缺省情况就是PEM,所以无需设置,另外支持DER
        //curl_easy_setopt(curl,CURLOPT_SSLCERTTYPE,"PEM");
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, true);
        curl_easy_setopt(curl, CURLOPT_CAINFO, pCaPath);
    }
    curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 3);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 3);
    res = curl_easy_perform(curl);
    curl_easy_cleanup(curl);
    return res;
}

int CHttpClient::Gets(const std::string & strUrl, std::string & strResponse, const char * pCaPath)
{
    CURLcode res;
    CURL* curl = curl_easy_init();
    if(NULL == curl)
    {
        return CURLE_FAILED_INIT;
    }
    if(m_bDebug)
    {
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
        curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, OnDebug);
    }
    curl_easy_setopt(curl, CURLOPT_URL, strUrl.c_str());
    curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, OnWriteData);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&strResponse);
    curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
    if(NULL == pCaPath)
    {
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);
    }
    else
    {
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, true);
        curl_easy_setopt(curl, CURLOPT_CAINFO, pCaPath);
    }
    curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 3);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 3);
    res = curl_easy_perform(curl);
    curl_easy_cleanup(curl);
    return res;
}

///////////////////////////////////////////////////////////////////////////////////////////////

void CHttpClient::SetDebug(bool bDebug)
{
    m_bDebug = bDebug;
}

HPR_INT32 CHttpClient::AddToMqSendQueue(string strMsg)
{
    if (strMsg == "")
    {
        return HPR_ERROR;
    }
    char* chMq = g_MemPool.MemAlloc(strMsg.length());
    if (chMq == NULL)
    {
        FIRE_ERROR("char* chActiveMq = MallocBuff(LARGE_LEN) fail");
        return HPR_ERROR;
    }
    HPR_Strncpy(chMq, strMsg.c_str(), strMsg.length());
    PushMq(chMq);
    return HPR_OK;
}
HPR_INT32    CHttpClient::Init()
{
    HPR_INT32    iRetVal = HPR_ERROR;
    m_strMqIp="";
    m_bExit=HPR_FALSE;
    do 
    {
        if (HPR_SemCreate(&m_iSendMqSem, 0) != HPR_OK)
        {
            LOG_ERROR("LoopSendMq list semaphore create failed!");
#if defined(OS_WINDOWS)
            m_iSendMqSem = HPR_INVALID_HANDLE;
#endif
            break;
        }
        m_hLoopPublishMq = HPR_Thread_Create(DoPublishAlarmThread, this, 0);
        if (m_hLoopPublishMq == HPR_INVALID_THREAD)
        {
            FIRE_ERROR("Create publish alarm thread failed!");
            break;
        }
        iRetVal = HPR_OK;
    } while (0);
    return iRetVal;
}
HPR_VOID    CHttpClient::Fini()
{
    m_bExit = HPR_TRUE;
    if (m_hLoopPublishMq != HPR_INVALID_THREAD)
    {
        HPR_Thread_Wait(m_hLoopPublishMq);
        m_hLoopPublishMq = HPR_INVALID_THREAD;
    }
#if defined(OS_WINDOWS)
    if (m_iSendMqSem != HPR_INVALID_HANDLE)
    {
        HPR_SemDestroy(&m_iSendMqSem);
        m_iSendMqSem = HPR_INVALID_HANDLE;
    }
#else
    HPR_SemDestroy(&m_iSendMqSem);
#endif
    ClearMqList();
}


HPR_INT32    CHttpClient::Connect()
{
        return HPR_OK;
}


HPR_VOID CHttpClient::DoPublishAlarm()
{
    int iStatus = 0;
    string strURL=CConfig::instance()->GetHttpURL();
    
    std::string strData= "hello Rabbit";
    string strResponse="";
    string strContent="";
    while (!m_bExit)
    {
        char* msg=PopMq();
        if (msg!=NULL)
        {
            strContent=string(msg);
            iStatus=Post(strURL,strContent,strResponse);
            if(iStatus!=CURLE_OK)
            {
                FIRE_ERROR("send data %s faild\n",msg);
                PushMq(msg);
                continue;
            }
            g_MemPool.MemRstore(msg);
            FIRE_INFO("send data sucess %s\n",msg);
        }    
    }
}

HPR_VOID CHttpClient::CheckMqStatus()
{

}

HPR_VOID CHttpClient::PushMq(char* chMqInfo)
{
    HPR_Guard lock(&m_iMutex);
    FIRE_INFO("PushActiveMq %s",chMqInfo);
    m_listRabbitMq.push_back(chMqInfo);
    HPR_SemPost(&m_iSendMqSem);
}

char* CHttpClient::PopMq()
{
    char* chMqInfo = NULL;

    do 
    {
        if (HPR_SemTimedWait(&m_iSendMqSem, 1000) != HPR_OK)
        {
            //FIRE_INFO("HPR_SemTimedWait(&m_iSendMqSem, 1000)");
            break;
        }

        HPR_Guard lock(&m_iMutex);
        if (m_listRabbitMq.size() == 0)
        {
            break;
        }
        else
        {
            chMqInfo = m_listRabbitMq.front();
            m_listRabbitMq.pop_front();
        }
        lock.Release();
    } while (0);

    return chMqInfo;
}

HPR_VOID CHttpClient::ClearMqList()
{
    {
        HPR_Guard lock(&m_iMutex);
        while(!m_listRabbitMq.empty())
        {
            char* chMqInfo = m_listRabbitMq.front();
            m_listRabbitMq.pop_front();
            g_MemPool.MemRstore(chMqInfo);
        }
    }
}

HPR_INT32    CHttpClient::CheckServerStatus( HPR_LONG lTimeOut)
{
    return HPR_OK;
}

 带有协议头的restfull接口

int CImageTransfer::Posts(const std::string & strUrl, const std::string & strPost, std::string & strResponse, const char * pCaPath)
{
    CURLcode res;
    CURL* curl = curl_easy_init();
    if(NULL == curl)
    {
        return CURLE_FAILED_INIT;
    }
    /*if(m_bDebug)
    {
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
        curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, OnDebug);
    }*/
    struct curl_slist *headers = NULL;

    //增加HTTP header
    headers = curl_slist_append(headers, "Accept:application/json");
    headers = curl_slist_append(headers, "Content-Type:application/json");
    headers = curl_slist_append(headers, "charset:utf-8");
    CBase64 pBase;
    string strCode="kqzhcg_hikvision :P3w6%kfm";
    strCode= pBase.Encode(strCode.c_str(),strCode.size());
    strCode="Authorization:"+strCode;
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_URL, strUrl.c_str());
    curl_easy_setopt(curl, CURLOPT_POST, 1);
    if (strPost!="")
    {
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, strPost.c_str());
        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, strPost.size());
    }
    //curl_easy_setopt(curl, CURLOPT_, headerlist);

    curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, OnWriteData);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&strResponse);
    curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
    if(NULL == pCaPath)
    {
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);
    }
    else
    {
        //缺省情况就是PEM,所以无需设置,另外支持DER
        //curl_easy_setopt(curl,CURLOPT_SSLCERTTYPE,"PEM");
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, true);
        curl_easy_setopt(curl, CURLOPT_CAINFO, pCaPath);
    }
    curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 3);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 3);
    res = curl_easy_perform(curl);
    curl_easy_cleanup(curl);
    return res;
}

自己编了一个股票监控软件,有如下功能,有兴趣的朋友可以下载;

(1)   个股监测。监测个股实时变化,可以监测个股大单交易、急速拉升和下降、主力入场和出场、股票最高点和最低点提醒。检测到最高点、最低点、主力进场点、主力退场点、急速拉升点、急速下跌点,给出语音或者声音提醒,不用再时刻看着大盘了,给你更多自由的时间;

(2)   大盘监测。监测大盘的走势,采用上证、深证、创业三大指数的综合指数作为大盘走势。并实时监测大盘的最高点和最低点、中间的转折点。

(3)   股票推荐。还能根据历史数据长期或短期走势进行分析,对股市3千多个股票进行分析对比,选出涨势良好的股票,按照增长速度从大到小排序,推荐给你涨势良好的股票;

下载地址:

1.0.3版本(修复大盘指数崩溃缺陷)下载地址:

链接:https://pan.baidu.com/s/1BJcTp-kdniM7VE9K5Kd3vg 提取码:003h

更新链接:

https://www.cnblogs.com/bclshuai/p/10621613.html

猜你喜欢

转载自www.cnblogs.com/bclshuai/p/8630532.html
今日推荐