热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

C++使用libcurl做HttpClient

当使用C++做HTTP客户端时,目前通用的做法就是使用libcurl。其官方网站的地址是http:curl.haxx.se,该网站主要提供了Curl和libcurl。Curl是命令

    当使用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。

    下载libcurl包,如果使用Linux平台,建议下载源文件编译;如果使用Windows平台,建议下载Win32 - MSVC,下载地址是:http://curl.haxx.se/download.html

#ifndef __HTTP_CURL_H__
#define __HTTP_CURL_H__

#include

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);

/**
* @brief HTTP GET请求
* @param strUrl 输入参数,请求的Url地址,如:http://www.baidu.com
* @param strResponse 输出参数,返回的内容
* @return 返回是否Post成功
*/
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 返回是否Post成功
*/
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 返回是否Post成功
*/
int Gets(const std::string & strUrl, std::string & strResponse, const char * pCaPath = NULL);

public:
void SetDebug(bool bDebug);

private:
bool m_bDebug;
};

#endif

#include "httpclient.h"#include "curl/curl.h"#include 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 = dynamic_cast((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_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;}int CHttpClient::Get(const std::string & strUrl, 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_READFUNCTION, NULL);	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, OnWriteData);	curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&strResponse);	/**	* 当多个线程都使用超时处理的时候,同时主线程中有sleep或是wait等操作。	* 如果不设置这个选项,libcurl将会发信号打断这个wait从而导致程序退出。	*/	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;}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_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);	if(NULL == pCaPath)	{		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);	}	else	{		//缺省情况就是PEM,所以无需设置,另外支持DER		//curl_easy_setopt(curl,CURLOPT_SSLCERTTYPE,"PEM");		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;}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_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_READFUNCTION, NULL);	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, OnWriteData);	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_bDebug = bDebug;}
 
 



推荐阅读
  • 阿里云ecs怎么配置php环境,阿里云ecs配置选择 ... [详细]
  • 优化局域网SSH连接延迟问题的解决方案
    本文介绍了解决局域网内SSH连接到服务器时出现长时间等待问题的方法。通过调整配置和优化网络设置,可以显著缩短SSH连接的时间。 ... [详细]
  • 深入解析Java虚拟机(JVM)架构与原理
    本文旨在为读者提供对Java虚拟机(JVM)的全面理解,涵盖其主要组成部分、工作原理及其在不同平台上的实现。通过详细探讨JVM的结构和内部机制,帮助开发者更好地掌握Java编程的核心技术。 ... [详细]
  • 深入解析动态代理模式:23种设计模式之三
    在设计模式中,动态代理模式是应用最为广泛的一种代理模式。它允许我们在运行时动态创建代理对象,并在调用方法时进行增强处理。本文将详细介绍动态代理的实现机制及其应用场景。 ... [详细]
  • 本文详细介绍如何使用arm-eabi-gdb调试Android平台上的C/C++程序。通过具体步骤和实用技巧,帮助开发者更高效地进行调试工作。 ... [详细]
  • PyCharm下载与安装指南
    本文详细介绍如何从官方渠道下载并安装PyCharm集成开发环境(IDE),涵盖Windows、macOS和Linux系统,同时提供详细的安装步骤及配置建议。 ... [详细]
  • Explore a common issue encountered when implementing an OAuth 1.0a API, specifically the inability to encode null objects and how to resolve it. ... [详细]
  • 1:有如下一段程序:packagea.b.c;publicclassTest{privatestaticinti0;publicintgetNext(){return ... [详细]
  • 本文详细介绍了如何在Linux系统上安装和配置Smokeping,以实现对网络链路质量的实时监控。通过详细的步骤和必要的依赖包安装,确保用户能够顺利完成部署并优化其网络性能监控。 ... [详细]
  • 深入理解Cookie与Session会话管理
    本文详细介绍了如何通过HTTP响应和请求处理浏览器的Cookie信息,以及如何创建、设置和管理Cookie。同时探讨了会话跟踪技术中的Session机制,解释其原理及应用场景。 ... [详细]
  • 本文介绍了一款用于自动化部署 Linux 服务的 Bash 脚本。该脚本不仅涵盖了基本的文件复制和目录创建,还处理了系统服务的配置和启动,确保在多种 Linux 发行版上都能顺利运行。 ... [详细]
  • 使用 Azure Service Principal 和 Microsoft Graph API 获取 AAD 用户列表
    本文介绍了一段通用代码示例,该代码不仅能够操作 Azure Active Directory (AAD),还可以通过 Azure Service Principal 的授权访问和管理 Azure 订阅资源。Azure 的架构可以分为两个层级:AAD 和 Subscription。 ... [详细]
  • 深入解析Spring Cloud Ribbon负载均衡机制
    本文详细介绍了Spring Cloud中的Ribbon组件如何实现服务调用的负载均衡。通过分析其工作原理、源码结构及配置方式,帮助读者理解Ribbon在分布式系统中的重要作用。 ... [详细]
  • HTTPS与TLS/SSL协议详解:握手及记录协议
    HTTPS,即HTTP over TLS/SSL,通过在HTTP通信层引入安全协议,确保数据传输的安全性。本文将深入探讨TLS/SSL协议的基本概念、HTTPS的必要性,以及TLS握手和记录协议的工作原理。 ... [详细]
  • Spring Cloud Config 使用 Vault 作为配置存储
    本文探讨了如何在Spring Cloud Config中集成HashiCorp Vault作为配置存储解决方案,基于Spring Cloud Hoxton.RELEASE及Spring Boot 2.2.1.RELEASE版本。文章还提供了详细的配置示例和实践建议。 ... [详细]
author-avatar
一个人的生活啦
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有