Http类

14 篇文章 0 订阅
12 篇文章 0 订阅

废话不多说,以后直接用这个

/*
* cycle.cc
*
*  Created on : 2016.12.30
*  Author : qiulu
*/
#include "http_helper.h"


bool HttpHelper::Init(Config *config)
{
    m_Config = config;
    if (m_Config->isMember("report_url") && (*m_Config)["report_url"].isString()) {
        m_RequestUrl = (*m_Config)["report_url"].asString();
    }
    else {
        log_error("config file has no report url");
        return false;
    }

    curl_global_init(CURL_GLOBAL_ALL);
    m_CurlHandler = curl_easy_init();
    if (NULL == m_CurlHandler) {
        log_error("can not initialize curl handler");
        return false;
    }

    m_CurlHeader = NULL;
    m_CurlHeader = curl_slist_append(m_CurlHeader, "Accept: */*");
    if (m_CurlHeader == NULL) {
        log_error("append header error");
        return false;
    }

    curl_easy_setopt(m_CurlHandler, CURLOPT_HTTPHEADER, m_CurlHeader);
    curl_easy_setopt(m_CurlHandler, CURLOPT_URL, m_RequestUrl.c_str());
    curl_easy_setopt(m_CurlHandler, CURLOPT_VERBOSE, 1);
    curl_easy_setopt(m_CurlHandler, CURLOPT_FOLLOWLOCATION, 0);
    curl_easy_setopt(m_CurlHandler, CURLOPT_READFUNCTION, NULL);
    curl_easy_setopt(m_CurlHandler, CURLOPT_NOSIGNAL, 1);
    curl_easy_setopt(m_CurlHandler, CURLOPT_CONNECTTIMEOUT_MS, 3000);
    curl_easy_setopt(m_CurlHandler, CURLOPT_TIMEOUT_MS, 4000);

    return true;
}

HttpHelper::~HttpHelper()
{
    if(NULL != m_CurlHeader)
        curl_slist_free_all(m_CurlHeader);
    curl_easy_cleanup(m_CurlHandler);
    curl_global_cleanup();  
}

bool HttpHelper::HttpRequst(const string &packet)
{
    CURLcode res;
    curl_easy_setopt(m_CurlHandler, CURLOPT_POSTFIELDSIZE, packet.length());
    curl_easy_setopt(m_CurlHandler, CURLOPT_POSTFIELDS, packet.c_str());
    res = curl_easy_perform(m_CurlHandler);

    if (res != CURLE_OK) {
        log_error("curl_easy_perform() failed: %s", curl_easy_strerror(res));
        return false;
    }
    return true;

}
/*
* cycle.h
*
*  Created on: 2016.12.30
*  Author: qiulu
*/
#ifndef _ACTIVESERVICE_HELPER_H_
#define _ACTIVESERVICE_HELPER_H_

#include "log.h"
#include "config.h"
#include <curl/curl.h>


class HttpHelper
{
public:
    bool Init(Config *config);
    bool HttpRequst(const string &packet);
    ~HttpHelper();
private:
    CURL *m_CurlHandler;
    Config *m_Config;
    string m_RequestUrl;
    struct curl_slist *m_CurlHeader;

};





#endif
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值