C++使用libcurl做HttpClient

当使用C++做HTTP客户端时,目前通用的做法就是使用libcurl。其官方网站的地址是http://curl.haxx.se/,该网站主要提供了Curl和libcurl。Curl是命令行工具,用于完成FTP, FTPS, HTTP, HTTPS, GOPHER, TELNET, DICT, FILE 以及 LDAP的命令的请求及接收回馈。libcurl提供给开发者,用于使用C++跨平台的开发各种网络协议的请求及响应。里面的文档非常齐全,不过都是英文的。

    本文提供最简单的demo使用libcurl开发HttpClient。主要包括同步的HTTP GET、HTTP POST、HTTPS GET、HTTPS POST。

#ifndef __CurlDemo__HttpCurl__
#define __CurlDemo__HttpCurl__
#include "cocos2d.h"
#include <string>
USING_NS_CC;
class CHttpClient
{
public:
    CHttpClient(void);
    ~CHttpClient(void);
    
    /**
     *@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地址,如:https://www.alipay.com
     *@param strResponse 输出参数,返回的内容
     *@return 返回是否成功
     */
    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 返回是否Posts成功
     */
    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 返回是否Gets成功
     */
    int Gets(const std::string& strUrl,std::string& strResponse,const char* pCaPath = NULL);
    
public:
    void setDebug(bool bDebug);
private:
    bool m_Debug;
};

#endif /* defined(__CurlDemo__HttpCurl__) */

#include "HttpCurl.h"
#include <string>

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
#include "../cocos2d/external/curl/include/ios/curl/curl.h"
#endif

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include "../cocos2d/external/curl/include/android/curl/curl.h"
#endif

CHttpClient::CHttpClient(void)
:m_Debug(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 OnWirteData(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_Debug)
    {
        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, OnWirteData);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&strResponse);
    curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
    curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 20);//连接时间
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 20);
    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();
    log("%d",NULL == curl?0:1);
    if(NULL == curl)
    {
        return CURLE_FAILED_INIT;
    }
    if(m_Debug)
    {
        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, OnWirteData);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA,(void*)& strResponse);
    
    curl_easy_setopt(curl, CURLOPT_NOSIGNAL,1);
    curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT,20);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT,20);
    res = curl_easy_perform(curl);
    if (res != CURLE_OK) {
        fprintf(stderr, "curl_easy_perform() failed:%s\n",curl_easy_strerror(res));
    }
    curl_easy_perform(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_Debug)
    {
        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,OnWirteData);
    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,10);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT,10);
    res = curl_easy_perform(curl);
    curl_easy_perform(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_Debug)
    {
        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,OnWirteData);
    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_Debug = bDebug;
}

使用
    CHttpClient* httpClient = new CHttpClient();
    httpClient->setDebug(false);
    std::string result;
    int res = httpClient->Get("http://www.baidu.com", result);
    _label1->setString(StringUtils::format("Get Statu = %d",res));
    log("result = %s",result.c_str());
    
    //post
    std::string result1;
    res = httpClient->Post("http://blog.csdn.net/yuxikuo_1?", "viewmode=list", result1);
    _label2->setString(StringUtils::format("Post Statu = %d",res));
    log("*******************");
    log("result = %s",result1.c_str());
    
    //gets
    httpClient->setDebug(false);
    std::string result2;
    int res2 = httpClient->Get("https://www.alipay.com", result2);
    _label3->setString(StringUtils::format("Get Statu = %d",res2));
    log("result = %s",result.c_str());

    
    delete httpClient;


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++使用libcurl库可以方便地进行网络通信,包括发送HTTP请求、下载文件等操作。下面是使用libcurl的一般步骤: 1. 引入头文件:在代码中引入libcurl的头文件,通常是`#include <curl/curl.h>`。 2. 初始化和清理:在使用libcurl之前,需要调用`curl_global_init()`函数进行初始化,并在使用完毕后调用`curl_global_cleanup()`函数进行清理。 3. 创建和配置CURL对象:使用`curl_easy_init()`函数创建一个CURL对象,并使用`curl_easy_setopt()`函数设置相关选项,如设置请求的URL、设置请求的方法、设置请求头等。 4. 执行请求:使用`curl_easy_perform()`函数执行请求,该函数会阻塞直到请求完成。 5. 处理响应:可以通过设置回调函数来处理响应数据,如保存到文件、打印到控制台等。 6. 清理资源:使用`curl_easy_cleanup()`函数释放CURL对象。 下面是一个简单的示例代码,演示了如何使用libcurl发送GET请求并将响应打印到控制台: ```cpp #include <iostream> #include <curl/curl.h> // 回调函数,处理响应数据 size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* response) { size_t totalSize = size * nmemb; response->append((char*)contents, totalSize); return totalSize; } int main() { CURL* curl; CURLcode res; std::string response; // 初始化 curl_global_init(CURL_GLOBAL_DEFAULT); // 创建CURL对象 curl = curl_easy_init(); if (curl) { // 设置请求的URL curl_easy_setopt(curl, CURLOPT_URL, "http://example.com"); // 设置回调函数 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); // 执行请求 res = curl_easy_perform(curl); if (res != CURLE_OK) { std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl; } // 打印响应数据 std::cout << response << std::endl; // 清理资源 curl_easy_cleanup(curl); } // 清理 curl_global_cleanup(); return 0; } ``` 这只是一个简单的示例,libcurl还提供了更多的功能和选项,可以根据具体需求进行配置和使用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值