热门标签 | 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;}
 
 



推荐阅读
  • CentOS系统安装与配置常见问题及解决方案
    本文详细介绍了在CentOS系统安装过程中遇到的常见问题及其解决方案,包括Vi编辑器的操作、图形界面的安装、网络连接故障排除等。通过本文,读者可以更好地理解和解决这些常见问题。 ... [详细]
  • 本文深入探讨了HTTP请求和响应对象的使用,详细介绍了如何通过响应对象向客户端发送数据、处理中文乱码问题以及常见的HTTP状态码。此外,还涵盖了文件下载、请求重定向、请求转发等高级功能。 ... [详细]
  • 本文详细探讨了HTML表单中GET和POST请求的区别,包括它们的工作原理、数据传输方式、安全性及适用场景。同时,通过实例展示了如何在Servlet中处理这两种请求。 ... [详细]
  • 本文详细介绍了如何在Kendo UI for jQuery的数据管理组件中,将行标题字段呈现为锚点(即可点击链接),帮助开发人员更高效地实现这一功能。通过具体的代码示例和解释,即使是新手也能轻松掌握。 ... [详细]
  • 技术分享:从动态网站提取站点密钥的解决方案
    本文探讨了如何从动态网站中提取站点密钥,特别是针对验证码(reCAPTCHA)的处理方法。通过结合Selenium和requests库,提供了详细的代码示例和优化建议。 ... [详细]
  • 使用 Azure Service Principal 和 Microsoft Graph API 获取 AAD 用户列表
    本文介绍了一段通用代码示例,该代码不仅能够操作 Azure Active Directory (AAD),还可以通过 Azure Service Principal 的授权访问和管理 Azure 订阅资源。Azure 的架构可以分为两个层级:AAD 和 Subscription。 ... [详细]
  • 本文介绍了如何通过 Maven 依赖引入 SQLiteJDBC 和 HikariCP 包,从而在 Java 应用中高效地连接和操作 SQLite 数据库。文章提供了详细的代码示例,并解释了每个步骤的实现细节。 ... [详细]
  • 在现代网络环境中,两台计算机之间的文件传输需求日益增长。传统的FTP和SSH方式虽然有效,但其配置复杂、步骤繁琐,难以满足快速且安全的传输需求。本文将介绍一种基于Go语言开发的新一代文件传输工具——Croc,它不仅简化了操作流程,还提供了强大的加密和跨平台支持。 ... [详细]
  • 本文探讨了在Linux系统上使用Docker时,通过volume将主机上的HTML5文件挂载到容器内部指定目录时遇到的403错误,并提供了解决方案和详细的操作步骤。 ... [详细]
  • 深入理解Redis的数据结构与对象系统
    本文详细探讨了Redis中的数据结构和对象系统的实现,包括字符串、列表、集合、哈希表和有序集合等五种核心对象类型,以及它们所使用的底层数据结构。通过分析源码和相关文献,帮助读者更好地理解Redis的设计原理。 ... [详细]
  • 本文详细介绍如何利用已搭建的LAMP(Linux、Apache、MySQL、PHP)环境,快速创建一个基于WordPress的内容管理系统(CMS)。WordPress是一款流行的开源博客平台,适用于个人或小型团队使用。 ... [详细]
  • 本文探讨了如何通过预处理器开关选择不同的类实现,并解决在特定情况下遇到的链接器错误。 ... [详细]
  • Symfony是一个功能强大的PHP框架,以其依赖注入(DI)特性著称。许多流行的PHP框架如Drupal和Laravel的核心组件都基于Symfony构建。本文将详细介绍Symfony的安装方法及其基本使用。 ... [详细]
  • CentOS 7.6环境下Prometheus与Grafana的集成部署指南
    本文旨在提供一套详细的步骤,指导读者如何在CentOS 7.6操作系统上成功安装和配置Prometheus 2.17.1及Grafana 6.7.2-1,实现高效的数据监控与可视化。 ... [详细]
  • 本文提供了在 Kali Linux 2020.01 x64 版本上安装 Docker 的详细步骤,包括环境准备、使用清华大学镜像源、配置 APT 仓库以及安装过程中的常见问题处理。 ... [详细]
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社区 版权所有