废话不多说,以后直接用这个
/*
* 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