【C++】使用 curl 库配置 HTTP 的 Post/Get 请求响应数据(封装一个简单类)
2023.7.18 Update: 【LibCurl】C++使用libcurl实现HTTP POST和GET
要想使用 LibCURL 库,首先需配置 CURL 库
参考链接:【C++开源库】Windows 下编译 libcurl 库
// 测试代码
#include <iostream>
using namespace std;;
int main()
{
curl_easy_init();
return 0;
}
// 没报错即配置成功
下面是上传json数据代码(下面以字符串为例子)
我手动拼接json字符串就不用配置json库了(配置json库在下面)
#include <curl/curl.h>
#include <string>
#include <exception>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
//下面是json数据格式
char szJsonData[1024];
memset(szJsonData, 0, sizeof(szJsonData));
string aa = "123";
string strJson = "{";
strJson += ""hex" : "" + aa + "",";
strJson += ""aa" : "123",";
strJson += ""bb" : "123",";
strJson += ""cc" : "123"";
strJson += "}";
strcpy(szJsonData, strJson.c_str());
try
{
CURL *pCurl = NULL;
CURLcode res;
// In windows, this will init the winsock stuff
curl_global_init(CURL_GLOBAL_ALL);
// get a curl handle
pCurl = curl_easy_init();
if (NULL != pCurl)
{
// 设置超时时间为1秒
curl_easy_setopt(pCurl, CURLOPT_TIMEOUT, 1);
// First set the URL that is about to receive our POST.
// This URL can just as well be a
// https:// URL if that is what should receive the data.
curl_easy_setopt(pCurl, CURLOPT_URL, "your URL");
// 设置http发送的内容类型为JSON
curl_slist *plist = curl_slist_append(NULL,
"Content-Type:application/json;charset=UTF-8");
curl_easy_setopt(pCurl, CURLOPT_HTTPHEADER, plist);
// 设置要POST的JSON数据
curl_easy_setopt(pCurl, CURLOPT_POSTFIELDS, szJsonData);
// Perform the request, res will get the return code
res = curl_easy_perform(pCurl);
// Check for errors
if (res != CURLE_OK)
{
printf("curl_easy_perform() failed:%s\n", curl_easy_strerror(res));
}
// always cleanup
curl_easy_cleanup(pCurl);
}
curl_global_cleanup();
}
catch (std::exception &ex)
{
printf("curl exception %s.\n", ex.what());
}
return 0;
}
配置 JSON 第三方库
cJSON
git clone https://github.com/DaveGamble/cJSON.git
# 拉取最新的 cJSON 版本
# 把文件夹下的 cJSON.h 和 cJSON.c 文件放在自己的项目文件夹下即可
jsoncpp
参考文章:https://www.cnblogs.com/tudou/p/14957646.html
下面是测试代码:
#include <iostream>
#include "json/json.h"
using namespace std;
int main()
{
string aa = "123";
//Json::Value jsonRoot; //定义根节点
Json::Value jsonItem; //定义一个子对象
jsonItem["hexImage"] =aa; //添加数据
//jsonRoot.append(jsonItem);
//jsonItem.clear(); //清除jsonItem
//jsonRoot["item"] = jsonItem;
cout << jsonItem.toStyledString() << endl; //输出到控制台
//解析字符串--输入json字符串,指定解析键名,得到键的值。
string str=jsonItem.toStyledString();
Json::Reader reader;
Json::Value root; //定义一个子对象
if (reader.parse(str, root))
{
string jsstr= root["hexImage"].asString();
cout << "jsstr:" << jsstr<< endl;
}
return 0;
}
下面给一个封装curl的类给大家使用。需要根据你需要的版本进行编译对应x86和x64
博主使用的是 VS2013 + x86 版本
// 头文件
#pragma once
#include <iostream>
using namespace std;
class Httpcurl
{
public:
//初始化curl库
void initcurl();
//释放curl库
void closecurl();
//接口请求
std::string requesthttp(std::string sendstr, std::string url);
};
// 实现文件
#include "Httpcurl.h"
#include <curl/curl.h>
//回调函数
size_t http_data_writer(void* data, size_t size, size_t nmemb, void* content)
{
long totalSize = size * nmemb;
//强制转换
std::string* symbolBuffer = (std::string*)content;
if (symbolBuffer)
{
symbolBuffer->append((char *)data, ((char*)data) + totalSize);
}
//cout << "symbolBuffer:" << symbolBuffer << endl;
//返回接受数据的多少
return totalSize;
}
void Httpcurl::initcurl()
{
//初始化curl库
curl_global_init(CURL_GLOBAL_ALL);
}
void Httpcurl::closecurl()
{
//释放内存,curl库
curl_global_cleanup();
}
//输入请求json,返回string
std::string Httpcurl::requesthttp(std::string sendstr, std::string url)
{
std::string strData;
CURL *pCurl = NULL;
CURLcode res;
// 获得一个句柄
pCurl = curl_easy_init();
if (NULL != pCurl)
{
// 设置超时时间为1秒
curl_easy_setopt(pCurl, CURLOPT_TIMEOUT, 1);
//设置url
curl_easy_setopt(pCurl, CURLOPT_URL, const_cast<char *>(url.c_str()));
// 设置http发送的内容类型为JSON格式
curl_slist *plist = curl_slist_append(NULL,
"Content-Type:application/json;charset=UTF-8");
curl_easy_setopt(pCurl, CURLOPT_HTTPHEADER, plist);
// 设置要POST的JSON数据
curl_easy_setopt(pCurl, CURLOPT_POSTFIELDS, sendstr.c_str());
// 设置回调函数
curl_easy_setopt(pCurl, CURLOPT_WRITEFUNCTION, http_data_writer);
//设置写数据
curl_easy_setopt(pCurl, CURLOPT_WRITEDATA, (void*)&strData);
// 请求成功
res = curl_easy_perform(pCurl);
// Check for errors
if (res != CURLE_OK)
{
printf("请求失败\n");
return "error";
}
else
{
cout << "请求成功" << endl;
}
// always cleanup
curl_easy_cleanup(pCurl);
}
return strData;
}
// main.cpp
#include <iostream>
#include "json/json.h"
#include "Httpcurl.h"
using namespace std;
int main(int argc, char *argv[])
{
Json::Value jsonItem; //定义一个子对象
jsonItem["aaa"] = "123"; //添加数据
jsonItem["bbb"] = "456"; //添加数据
string str = jsonItem.toStyledString();
string url = "http://localhost:8080/test";
Httpcurl httpcurl;
httpcurl.initcurl();
cout << httpcurl.requesthttp(str,url) << endl;
httpcurl.closecurl();
getchar();
return 0;
}
响应什么大家自己用web写个接口测试吧。我这里是获取了它返回的数据。
也可以根据返回的状态码进行判断,是否接收成功。根据实际要求操作。
【C++】使用 curl 库配置 HTTP 的 Post/Get 请求响应数据(封装一个简单类)的更多相关文章
- 使用libzplay库封装一个音频类
装载请说明原地址,谢谢~~ 前两天我已经封装好一个duilib中使用的webkit内核的浏览器控件和一个基于vlc的用于播放视频的视频控件,这两个控件可以分别用在放酷狗播放器的乐库功能和MV ...
- C 封装一个简单二叉树基库
引文 今天分享一个喜欢佩服的伟人,应该算人类文明极大突破者.收藏过一张纸币类型如下 那我们继续科普一段关于他的简介 '高斯有些孤傲,但令人惊奇的是,他春风得意地度过了中产阶级的一生,而 没有遭受到冷 ...
- SpringMVC_01 SpringMVC五大组件、SpringMVC编程步骤(不使用注解进行配置)、SpringMVC编程步骤(利用注解进行配置)、参数获取、响应数据
1 什么是SpringMVC 是一个mvc框架,用来简化基于mvc架构的web应用程序的 开发. 2 SpringMVC五大组件 DispatcherServlet (前端控制器) HanlderMa ...
- 嵌入式 Linux下curl库API简单介绍
1:CURLcode curl_global_init(long flags); 这个函数全局需要调用一次(多次调用也可以,不过没有必要), 所以这也是把Curlplus设计成单体类的原因,curl_ ...
- CURL库在C++程序中的运用浅析
最近由于要做一个爬虫项目,要对很多网站进行爬取,所以一直都在看这方面的文章.在翻阅了很多资料后,下载了一个curl库,着实对项目有了很大的帮助. 一.LibCurl基本编程框架 二.一些基本的函数 三 ...
- [转]linux 下 使用 c / c++ 调用curl库 做通信开发
example: 1. http://curl.haxx.se/libcurl/c/example.html 2. http://www.libcurl.org/book: 1. http:/ ...
- Spring Boot 揭秘与实战 自己实现一个简单的自动配置模块
文章目录 1. 实战的开端 – Maven搭建 2. 参数的配置 - 属性参数类 3. 真的很简单 - 简单的服务类 4. 自动配置的核心 - 自动配置类 5. spring.factories 不要 ...
- 从零开始配置一个简单的webpack打包
一.基础配置 1.创建一个名为demo-webpack的文件夹(名称随意) 2.初始化一个package.json文件 //在cmd窗口中使用以下命令快速创建 npm init -y 3.安装webp ...
- linux编译curl库的动态库so(转)
转载请注明出处:帘卷西风的专栏(http://blog.csdn.NET/ljxfblog) curl库是一个很强大的http开源库,c++里面能够很方便的和http服务器交互. 最近项目开始内测,开 ...
- curl库 c语言的curl 编程
c语言的curl 编程 [Linux@centos-64-min exercise]# gcc -Wall -o curltest curltest.c /tmp/ccosVANi.o: In fun ...
随机推荐
- 【Javaweb】四(关于接口类的作用)
这里我们还是以房产信息管理系统的题目举例: 发现在DAO层和service层都有接口类(注:impl是实现类) 为什么要用接口,不直接写实现类: 1.简单.规范性:这些接口不仅告诉开发人员你需要实现那 ...
- IDEA:自动生成方法注释并添加 @param 参数(Java+Kotlin)
在用 Java 或 Kotlin 编写方法时建议编写完善的注释,包含每个参数的意义和返回的内容,下面介绍在 IDEA 中自动生成方法注释的技巧. 第二张图按照图片填写就好了 ③(注意是*不是/*) * ...
- extern关键字的用法
extern关键字的理解 extern是C/C++语言中的一个关键字,用于声明一个变量或函数具有外部链接性(external linkage),即这些变量或函数可以被其他文件访问. 在C/C++中,如 ...
- python中的post请求
用python来验证接口正确性,主要流程有4步: 1 设置url 2 设置消息头 3 设置消息体 4 获取响应 5 解析相应 6 验证数据 Content-Type的格式有四种:分别是applicat ...
- WPF DataGrid真正意义上开箱即用的原生可动态更新全选状态的DataGridCheckBox
本文由 飞羽流星(Flithor/毛茸茸松鼠先生/Squirrel.Downy)原创,欢迎分享转载,但禁止以原创二次发布原位地址:https://www.cnblogs.com/Flithor/p/1 ...
- Linux笔记02: Linux环境_2.1虚拟机软件VMware
2.1 虚拟机软件VMware 如果直接在计算机上安装多个操作系统,同一个时刻只能运行一个操作系统,切换系统需重启计算机.VMware可以使用户在一台计算机上同时运行多个操作系统(如Windows.L ...
- Chrome扩展的核心:manifest 文件(上)
大家好,我是dom哥.我正在写关于 Chrome 扩展开发的系列文章,感兴趣的可以点个小星星. Chrome 在全球浏览器市场份额独占 6 成,无论是对普通用户还是开发者,都是电脑里的必备利器.Chr ...
- springboot——入门案例
真简单啊 springboot 学了入门案例,有感而发 首先是一个自带的配置文件: package com.example.springboot_01; import org.springframew ...
- Cocos Creator性能调优
一. 为什么要做性能优化 性能:是程序的一种优秀的能力.唤醒快.运行持久.稳定 这种能力正在游戏上能让你的用户感觉很爽,特征表现为加载快.运行流畅.不卡顿. 所以,性能优化的终极目标是,让你的用户体验 ...
- offline RL | Pessimistic Bootstrapping (PBRL):在 Q 更新中惩罚 uncertainty,拉低 OOD Q value
论文题目:Pessimistic Bootstrapping for Uncertainty-Driven Offline Reinforcement Learning,ICLR 2022,6 6 8 ...