#pragma once
#include <map>
#include <string>
class CHttpHelp
{
public:
CHttpHelp(void);
~CHttpHelp(void);
static void InitCURL();
static void CleanupCURL();
std::string get_value(std::string url, int timeOut = 500); //默认10毫秒
std::string post_value(std::string url, std::string szpara,int timeout = 500);
void SetReqReceive(std::string str);
private:
std::string m_Res;
std::string m_strUrl;
};
#include "StdAfx.h"
#include "curl/curl.h"
#include "HttpHelp.h"
CHttpHelp::CHttpHelp(void)
{
}
CHttpHelp::~CHttpHelp(void)
{
}
void CHttpHelp::InitCURL()
{
curl_global_init(CURL_GLOBAL_ALL);
}
void CHttpHelp::CleanupCURL()
{
curl_global_cleanup();
}
size_t CHttpHelp_OnHttpReqReceive(void *buffer, size_t size, size_t nmemb, void*userp)
{
std::string tempRes = (char *) buffer;
tempRes = tempRes.substr(0, nmemb);
CHttpHelp * hander = (CHttpHelp *)userp;
hander->SetReqReceive(tempRes);
return size * nmemb;
}
void CHttpHelp::SetReqReceive(std::string str)
{
m_Res = m_Res + str;
}
std::string CHttpHelp::get_value(std::string url, int timeOut)
{
m_Res = "";
CURL *curl;
CURLcode curl_code;
curl = curl_easy_init();
if ( !curl ) {
return m_Res;
}
curl_easy_setopt( curl, CURLOPT_URL, url.c_str());
curl_easy_setopt( curl, CURLOPT_WRITEDATA, (void*)this);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeOut);
curl_code = curl_easy_setopt( curl, CURLOPT_WRITEFUNCTION, CHttpHelp_OnHttpReqReceive);
curl_code = curl_easy_perform( curl );
if (curl_code != CURLE_OK)
{
}
curl_easy_cleanup(curl);
return m_Res;
}
std::string CHttpHelp::post_value(std::string url,std::string szpara, int timeout)
{
m_Res = "";
CURL *curl;
CURLcode curl_code;
curl = curl_easy_init();
if (!curl) {
return m_Res;
}
curl_easy_setopt(curl, CURLOPT_POST, 1); // post req
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, szpara.c_str());
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)this);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
curl_code = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CHttpHelp_OnHttpReqReceive);
curl_code = curl_easy_perform(curl);
if (curl_code != CURLE_OK)
{
}
curl_easy_cleanup(curl);
return m_Res;
}
curl库实现get及post请求
最新推荐文章于 2025-03-10 14:13:07 发布