c++配置http/post请求接收json数据

2023-05-16

照着教程编译操作都没问题
首先是配置curl库
给一个别人的编译链接curl库 vs2017:亲测可用
c++编译curl库

测试代码:

#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库:
有两个版本,一个支持c++11 是1.几版本的,一个不支持0.10.7(我用的是这个)
同样也是找别人的:亲测可用
c++配置json库

下面是测试代码

#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
包含库路径:
E:\C++库\curl库\cur\libcurl-vc14-x86-release-static-ipv6-sspi-winssl\include
预处理器:
CURL_STATICLIB
_CRT_SECURE_NO_WARNINGS
包含库路径和依赖库名字:
把lib拷到对应的文件下
依赖库:
libcurl_a.lib
ws2_32.lib
winmm.lib
wldap32.lib
Crypt32.lib
Normaliz.lib

头文件

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


};


cpp文件

#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写个接口测试吧。我这里是获取了它返回的数据。
也可以根据返回的状态码进行判断,是否接收成功。根据实际要求操作。
在这里插入图片描述

下面给一个官方的curlAPI地址:
官方API地址

参考文章:
网友幸福官请求响应
curl使用教程

更新2022-02-09

解析json

//获取指定关键字的值   "name\":\"abc"
string getValue(Json::Value jsonItem,string key)
{
	if (jsonItem.isMember(key))
	{
		return jsonItem[key].asString();
	}
	return "error";
}
//获取某个根结点的值 "aa\":{\"bb\":\"123\"}}"
Json::Value getRootValue(string str, string key)
{
	Json::Reader reader;
	Json::Value root;
	Json::Value value;
	if (reader.parse(str, root))
	{
		int size = root.size();   // 根结点个数

		for (int j = 0; j < size; j++)
		{
			if (!root[key].isNull())
			{
				return root[key];
			}
		}
	}
	return value;
}
//json转string
string str;
str = jsonItem.toStyledString();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

c++配置http/post请求接收json数据 的相关文章

  • 编写大 JSON 文件避免内存不足问题的最佳方法

    首先 请注意今天是我第一天GSON 我正在尝试使用编写 Json 文件GSON图书馆 我有几千个JsonObjects里面一个ArrayList 当写入 Json 文件时 它应该看起来与此类似 hash index 00102x05h06l
  • LinkedIn OAuth 缺少必需参数“client_id”

    我正在使用 LinkedIn API 并尝试发出请求 但是当我尝试获取 accesstoken 时 我在 json 打印中收到以下错误 Array error gt missing parameter error description g
  • 使用rapidjson设置浮点精度

    有没有办法控制使用rapidjson生成的JSON的输出精度 例如 writer String length writer Double 1 0 3 0 这会生成类似以下内容的内容 length 0 33333333 我发送了很多值 并且几
  • HTTP PUT 请求通常如何发出?

    我知道 HTTP PUT 是一个幂等请求 根据定义 引用自rfc http www w3 org Protocols rfc2616 rfc2616 sec9 html The PUT method requests that the en
  • 如何在 Java 中将 hashmap 转换为 JSON 对象 [关闭]

    Closed 这个问题需要细节或清晰度 help closed questions 目前不接受答案 如何在 Java 中将 hashmap 转换或转换为 JSON 对象 然后再次将 JSON 对象转换为 JSON 字符串 您可以使用 new
  • 将数据从 jQuery 传递到 PHP 以进行 ajax post

    你好 我是一个使用 jQuery 和 Ajax 的新手 我正在尝试使用 Jquery POST 方法将数据提交到服务器 我传递的数据是一个字符串 现在我无法理解如何传递数据以及如何检索数据 我尝试搜索有关我的问题的文章 但没有找到 我相信我
  • RxJS Angular2 在 Observable.forkjoin 中处理 404

    我目前正在链接一堆 http 请求 但是在订阅之前我无法处理 404 错误 My code 在模板中 service getData subscribe data gt this items data err gt console log
  • 我应该使用哪种协议来传输音频(非直播)? [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • 在 portlet 中使用 json 对象响应 http 请求

    我是liferay portlet 开发的初学者 我正在开发一个portlet 它接收http get 请求 处理一些信息 然后必须返回一个json 对象 我的问题是我的 portlet 发送整个 html 页面而不仅仅是 json 对象
  • Python请求响应以utf-8编码但无法解码

    我正在尝试使用 python 抓取我的messenger com facebook Messenger 聊天记录 并且我使用谷歌浏览器开发工具来查看聊天历史记录的 POST 请求 并且我已将整个标头和正文复制为请求可以使用的格式 我得到 H
  • 如何对具有无效值的属性使用 JSON.net 的默认值

    我正在使用 Newtonsoft JSON 库来反序列化来自 Web 服务的响应 问题是某些字段包含无效值 例如 一条记录上的一个字段包含一个 T 表示该字段应该是数字 我想做的是将无效字段的值设置为 null 或其他默认值 我的所有属性都
  • 特定字段的自定义 Jackson 序列化器

    我希望为同一对象提供多个杰克逊反序列化器 所有这些都基于自定义注释 理想情况下 我有一个 POJO 例如 public class UserInfo Redacted String ssn String name 在 正常 条件下 我希望该
  • 使用Log4j在日志中输出Spark应用程序id

    我有一个用于 Spark 应用程序的自定义 Log4j 文件 我想输出 Spark 应用程序 ID 以及消息和日期等其他属性 因此 JSON 字符串结构如下所示 name time date level thread message app
  • GSON 没有为接口类型调用我的 TypeAdapter

    GSON 似乎在使用某种技巧 它查看 JavaBean 的内部字段 而不是使用可公开访问的属性信息 不幸的是 这对我们来说不会成功 因为我们神奇地创造的豆子充满了我不希望它存储的私人领域 Test public void testJson
  • 为什么我的自定义 JSONEncoder.default() 忽略布尔值?

    我想将字典转换为带有布尔值的 JSON 字符串True值转换为数字1和布尔值False值转换为数字0 我正在使用一个JSONEncoder子类 但它似乎忽略布尔值 import json class MyEncoder json JSONE
  • 如何从数组中删除空数组值(“”)?

    我有一个二维数组 是用 jQuery 从 html 表生成的 但有些值是空的 所以 被展示 如何删除空值 table tr th 1A th th 1B th th 1C th tr tr td 2A td td 2B td td 2C t
  • 摆脱浏览器控制台中的 401(未经授权)ajax 错误

    我正在使用 javascript 通过 api 调用jQuery ajax http api jquery com jQuery ajax 称呼 如果用户未经过身份验证 API 会响应 401 并且我只想针对此调用忽略此错误 我已经尝试了
  • 如何在 Ruby on Rails 中读取远程文件的内容?

    这是我的文件 http example com test txt http example com test txt 我必须阅读以下内容http example com test txt http example com test txt
  • 如何在使用 Json4s 序列化期间重命名字段?

    如何轻松重命名 json4s 中的字段名称 从他们的文档中 我尝试了以下代码片段 但它似乎没有重命名serial字段到id case class Person serial Int firstName String val rename F
  • Matlab 的快速 JSON 解析器

    您知道 Matlab 中有一个非常快速的 JSON 解析器吗 目前我正在使用JSONlab http www mathworks com matlabcentral fileexchange 33381 jsonlab a toolbox

随机推荐

  • 【GITEE】解决 Push rejected

    问题背景 xff1a 更新了台式电脑后 xff0c 从gitlee上拉了代码 xff0c 重新push后就一直报错 xff1a Push single to origin single was rejected by remote 问题解决
  • 一小时学会Python3爬虫基础(二)基础语法 输入输出 关键字 注释

    目录 前言集成环境 编辑器基本语法缩进换行标识符关键字注释输入 输出总结 前言 python作为一门编程语言 xff0c 也跟其他语言一样有自己的逻辑语法 xff0c 那什么是语法 xff1f 跟人一样每个人都有自己说话一套方法 集成环境
  • windows 生成self-sign证书

    打开powershell 管理员身份运行 New SelfSignedCertificate CertStoreLocation Cert LocalMachine My DnsName 34 mysite local 34 Friendl
  • 一小时学会Python3爬虫基础(四)完整解析格式化输出和数据类型转换

    目录 前言格式化输出格式化符号 s格式化函数format格式化表示 f string 转义符和结束符 n意思就是 换行 new line t 叫做水平制表符 tab xff0c r 是回车符carriage return结束符 数据类型转换
  • 一小时学会Python3爬虫基础(七)高级数据的全部操作:字典

    目录 前言字典1 字典格式2 创建有效字典2 创建空字典3 字典类型转换 字典增加和修改1 增加2 修改 字典查找1 key键查找2 get 3 keys 4 values 5 items 字典循环遍历1 遍历字典的key值2 遍历字典的v
  • Python处理异常代码的基本操作,原来都大同小异!

    目录 什么是异常 xff1f 如何捕获异常 xff1f 1 异常的写法2 捕获指定异常3 捕获多个异常4 捕获异常的描述5 捕获所有异常6 异常的else7 finally8 自定义异常模块9 异常传递思路 总结 什么是异常 xff1f 简
  • python的模块与包的关系

    模块和包的概念 python中的模块 xff0c 其实就是一个python的文件 xff0c 包含了很多类和函数 xff0c 基本上都是可以向外调用的 xff0c 或者整个文件都用来处理某个操作 xff0c 我们使用库和框架就是由模块和包构
  • 一小时学会Python基础练习的十四个练手题

    目录 1到100的加法搬家具办公室人员分配猜拳游戏乘公交车吃苹果九九乘法表烤地瓜奇偶100内相加三角形正方形文件备份学员管理系统 xff08 函数版 xff09 学员管理系统 xff08 面向对象版 xff09 mainmangerSyst
  • ROS Topic (话题通信总结)

    拿到一个功能包 xff0c 先运行一下 xff08 以turtlesim为例子 xff09 xff1a rusrun turtlesim turtlesim node 然后使用 rqt graph 和rostopic list 大致了解有哪
  • vector函数用法

    一维 基本用法 xff1a 1 头文件 include lt vector gt 2 创建vector对象 xff0c vector lt int gt vec 3 尾部插入数字 xff1a vec push back a 4 使用下标访问
  • Jetson nano串口的使用——UART

    UART串口使用两条杜邦线就可以实现数据发送和接收 xff0c 可以很方便的与其他扩展进行数据连接 xff0c 比如微雪的L76X GPS HAT就可以直接连接40Pin的GPIO接口通过UART串口进行数据传递 接下来具体说明Jetson
  • Python中[-1]、[:-1]、[::-1]、[n::-1]、[:,:,0]、[…,0]、[…,::-1] 的理解

    在python中会出现 1 1 1 n 1 0 0 1 xff0c 他们分别是什么意思呢 xff0c 这里就来详尽的说一下 xff1a 下面的a 61 1 2 3 4 5 1 xff1a 列表最后一项 1 xff1a 从第一项到最后一项 原
  • 贴片电阻字码阻值对照表

  • 使用sphinx生成python项目文档

    1 pip install sphinx 2 sphinx quickstart 3 修改 conf py import os import sys sys path insert 0 os path abspath 39 39 确保mod
  • 免费商用字体有哪些

    免费商用字体有哪些 一 思源字体 xff0c 可以免费商用的有 思源黑体 xff0c 思源宋体 xff0c 思源柔黑体 二 方正字体 xff0c 方正类字体可以免费商用的有 xff1a 方正仿宋 xff08 简 xff0c 繁 xff09
  • Qt:16进制字符串数据转整数数值函数

    span class token comment 16进制字符串数据转整数数值 span span class token keyword int span Setting span class token operator span sp
  • ESP-12F开发环境

    ESP 12F可以使用arduino IDE快速开发 1 首先安装arduino IDE xff1a 搜索直接下载即可 2 在文件 gt 首选项 gt 附加开发板管理器网址中添加ESP8266开发板 xff1a 网址 xff1a http
  • 第1章 电子设计与制作基础

    1 电子系统的分类 模拟电子系统数字电子系统模拟 数字混合系统微处理器 xff08 单片机 嵌入式 xff09 电子系统 2 电子系统的定义 通常 xff0c 将由电子元器件或部件组成的能够产生 传输 采集或处理电信号及信息的客观实体称为电
  • python requests timeout参数

    首先发一下牢骚 xff1a 不管是抄袭还是转载 xff0c 有点新东西行不行 xff0c 一味的转载有什么用呢 xff1f 东西还以那点东西 xff0c 让想解决问题的人查看一些一摸一样的文章 xff0c 只会浪费查询者的时间 况且 xff
  • c++配置http/post请求接收json数据

    照着教程编译操作都没问题 首先是配置curl库 给一个别人的编译链接curl库 vs2017 xff1a 亲测可用 c 43 43 编译curl库 测试代码 xff1a span class token macro property spa