client.cpp
#include "httpclient.h"
#include "curl/curl.h"
#include <string>
#include <cstdio>
#include <iostream>
using namespace std;
#pragma comment(lib,"libcurl.lib")
//#pragma comment(lib,"curllib_static.lib")
//#pragma comment(lib,"ssleay32.lib")
//#pragma comment(lib,"libcurl_imp.lib")
//#pragma comment(lib,"libeay32.lib")
//#pragma comment(lib,"openldap.lib")
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 = ((std::string *)lpVoid);//dynamic_cast<std::string*>
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;
}
void CHttpClient::SetDebug(bool bDebug)
{
m_bDebug = bDebug;
}
int main()
{
CHttpClient client;
string url="localhost/recieve.php";//http://192.168.0.116/lanyun/?option=ajax2&a=plan_result&type=1&nologin=1
string post="type=3&mac=10:00:00:00:00:00&name=111";
string psend;
client.SetDebug(FALSE);
int a=client.Post(url,post,psend);
printf("%d\n%s\n",a,psend.c_str());
return 0;
}
httpclient.h
#ifndef __HTTP_CURL_H__
#define __HTTP_CURL_H__
#include <string>
class CHttpClient
{
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);
void SetDebug(bool bDebug);
private:
bool m_bDebug;
};
#endif