c++ http请求,json解析

2023-05-16

一、文章内容

解决c++http请求以及对返回结果json串进行解析,使用jsoncpp库

二、安装jsoncpp插件

vs2015通过NuGet直接安装jsoncpp到项目下





安装好之后,会在项目下有个package包,这个包下面就是jsoncpp库。

三、可以上代码了

http请求

WininetHttp.h文件

#pragma once
#include <iostream>
#include <windows.h>
#include <wininet.h>

using namespace std;

//每次读取的字节数
#define READ_BUFFER_SIZE        4096

enum HttpInterfaceError
{
	Hir_Success = 0,        //成功
	Hir_InitErr,            //初始化失败
	Hir_ConnectErr,            //连接HTTP服务器失败
	Hir_SendErr,            //发送请求失败
	Hir_QueryErr,            //查询HTTP请求头失败
	Hir_404,                //页面不存在
	Hir_IllegalUrl,            //无效的URL
	Hir_CreateFileErr,        //创建文件失败
	Hir_DownloadErr,        //下载失败
	Hir_QueryIPErr,            //获取域名对应的地址失败
	Hir_SocketErr,            //套接字错误
	Hir_UserCancel,            //用户取消下载
	Hir_BufferErr,            //文件太大,缓冲区不足
	Hir_HeaderErr,            //HTTP请求头错误
	Hir_ParamErr,            //参数错误,空指针,空字符
	Hir_UnknowErr,
};
enum HttpRequest
{
	Hr_Get,
	Hr_Post
};
class CWininetHttp
{
public:
	CWininetHttp(void);
	~CWininetHttp(void);

public:
	//  通过HTTP请求:Get或Post方式获取JSON信息 [3/14/2017/shike]
	const std::string RequestJsonInfo(const std::string& strUrl,
		HttpRequest type = Hr_Get,
		std::string lpHeader = "",
		std::string lpPostData = "");
protected:
	// 解析卡口Json数据 [3/14/2017/shike]
	void ParseJsonInfo(const std::string &strJsonInfo);

	// 关闭句柄 [3/14/2017/shike]
	void Release();

	// 释放句柄 [3/14/2017/shike]
	void ReleaseHandle(HINTERNET& hInternet);

	// 解析URL地址 [3/14/2017/shike]
	void ParseURLWeb(std::string strUrl, std::string& strHostName, std::string& strPageName, WORD& sPort);

	// UTF-8转为GBK2312 [3/14/2017/shike]
	char* UtfToGbk(const char* utf8);

private:
	HINTERNET            m_hSession;
	HINTERNET            m_hConnect;
	HINTERNET            m_hRequest;
	HttpInterfaceError    m_error;
};

WininetHttp.cpp文件

/*************************************************
File name  :  WininetHttp.cpp
Description:  通过URL访问HTTP请求方式获取JSON
Author     :  shike
Version    :  1.0
Date       :  2016/10/27
Copyright (C) 2016 -  All Rights Reserved
*************************************************/
#include "WininetHttp.h"
#include <json/json.h>
//#pragma comment(lib, "jsoncpp.lib")
#include <fstream>
#pragma comment(lib, "Wininet.lib")
#include <tchar.h>
using namespace std;

CWininetHttp::CWininetHttp(void) :m_hSession(NULL), m_hConnect(NULL), m_hRequest(NULL)
{
}

CWininetHttp::~CWininetHttp(void)
{
	Release();
}

//  通过HTTP请求:Get或Post方式获取JSON信息 [3/14/2017/shike]
const std::string CWininetHttp::RequestJsonInfo(const std::string& lpUrl,
	HttpRequest type/* = Hr_Get*/,
	std::string strHeader/*=""*/,
	std::string strPostData/*=""*/)
{
	std::string strRet = "";
	try
	{
		if (lpUrl.empty())
		{
			throw Hir_ParamErr;
		}
		Release();
		m_hSession = InternetOpen(_T("Http-connect"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, NULL);    //局部

		if (NULL == m_hSession)
		{
			throw Hir_InitErr;
		}

		INTERNET_PORT port = INTERNET_DEFAULT_HTTP_PORT;
		std::string strHostName = "";
		std::string strPageName = "";

		ParseURLWeb(lpUrl, strHostName, strPageName, port);
		printf("lpUrl:%s,\nstrHostName:%s,\nstrPageName:%s,\nport:%d\n", lpUrl.c_str(), strHostName.c_str(), strPageName.c_str(), (int)port);

		m_hConnect = InternetConnectA(m_hSession, strHostName.c_str(), port, NULL, NULL, INTERNET_SERVICE_HTTP, NULL, NULL);

		if (NULL == m_hConnect)
		{
			throw Hir_ConnectErr;
		}

		std::string strRequestType;
		if (Hr_Get == type)
		{
			strRequestType = "GET";
		}
		else
		{
			strRequestType = "POST";
		}

		m_hRequest = HttpOpenRequestA(m_hConnect, strRequestType.c_str(), strPageName.c_str(), "HTTP/1.1", NULL, NULL, INTERNET_FLAG_RELOAD, NULL);
		if (NULL == m_hRequest)
		{
			throw Hir_InitErr;
		}

		DWORD dwHeaderSize = (strHeader.empty()) ? 0 : strlen(strHeader.c_str());
		BOOL bRet = FALSE;
		if (Hr_Get == type)
		{
			bRet = HttpSendRequestA(m_hRequest, strHeader.c_str(), dwHeaderSize, NULL, 0);
		}
		else
		{
			DWORD dwSize = (strPostData.empty()) ? 0 : strlen(strPostData.c_str());
			bRet = HttpSendRequestA(m_hRequest, strHeader.c_str(), dwHeaderSize, (LPVOID)strPostData.c_str(), dwSize);
		}
		if (!bRet)
		{
			throw Hir_SendErr;
		}

		char szBuffer[READ_BUFFER_SIZE + 1] = { 0 };
		DWORD dwReadSize = READ_BUFFER_SIZE;
		if (!HttpQueryInfoA(m_hRequest, HTTP_QUERY_RAW_HEADERS, szBuffer, &dwReadSize, NULL))
		{
			throw Hir_QueryErr;
		}
		if (NULL != strstr(szBuffer, "404"))
		{
			throw Hir_404;
		}

		while (true)
		{
			bRet = InternetReadFile(m_hRequest, szBuffer, READ_BUFFER_SIZE, &dwReadSize);
			if (!bRet || (0 == dwReadSize))
			{
				break;
			}
			szBuffer[dwReadSize] = '\0';
			strRet.append(szBuffer);
		}
	}
	catch (HttpInterfaceError error)
	{
		m_error = error;
	}
	return std::move(strRet);
}

// 解析Json数据 [11/8/2016/shike]
void CWininetHttp::ParseJsonInfo(const std::string &strJsonInfo)
{
	Json::Reader reader;                                    //解析json用Json::Reader
	Json::Value value;                                        //可以代表任意类型
	if (!reader.parse(strJsonInfo, value))
	{
		printf("error!");
	}
	if (!value["result"].isNull())
	{
		int nSize = value["result"].size();
		for (int nPos = 0; nPos < nSize; ++nPos)                //对数据数组进行遍历
		{
			//PGCARDDEVDATA stru ;
			//stru.strCardName        = value["result"][nPos]["tollgateName"].asString();
			//stru.strCardCode        = value["result"][nPos]["tollgateCode"].asString();
			//std::string strCDNum    = value["result"][nPos]["laneNumber"].asString();    //增加:车道总数
			//stru.nLaneNum            = atoi(strCDNum.c_str());
			//std::string strLaneDir    = value["result"][nPos]["laneDir"].asString();        //增加:车道方向,进行规则转换
			//stru.strLaneDir            = TransformLaneDir(strLaneDir);
			//stru.dWgs84_x            = value["result"][nPos]["wgs84_x"].asDouble();
			//stru.dWgs84_y            = value["result"][nPos]["wgs84_y"].asDouble();
			//stru.dMars_x            = value["result"][nPos]["mars_x"].asDouble();
			//stru.dMars_y            = value["result"][nPos]["mars_y"].asDouble();
			//lstCardDevData.emplace_back(stru);
		}
	}
}

// 解析URL地址 [3/14/2017/shike]
void CWininetHttp::ParseURLWeb(std::string strUrl, std::string& strHostName, std::string& strPageName, WORD& sPort)
{
	sPort = 80;
	string strTemp(strUrl);
	std::size_t nPos = strTemp.find("http://");
	if (nPos != std::string::npos)
	{
		strTemp = strTemp.substr(nPos + 7, strTemp.size() - nPos - 7);
	}

	nPos = strTemp.find('/');
	if (nPos == std::string::npos)    //没有找到
	{
		strHostName = strTemp;
	}
	else
	{
		strHostName = strTemp.substr(0, nPos);
	}

	std::size_t nPos1 = strHostName.find(':');
	if (nPos1 != std::string::npos)
	{
		std::string strPort = strTemp.substr(nPos1 + 1, strHostName.size() - nPos1 - 1);
		strHostName = strHostName.substr(0, nPos1);
		sPort = (WORD)atoi(strPort.c_str());
	}
	if (nPos == std::string::npos)
	{
		return;
	}
	strPageName = strTemp.substr(nPos, strTemp.size() - nPos);
}

// 关闭句柄 [3/14/2017/shike]
void CWininetHttp::Release()
{
	ReleaseHandle(m_hRequest);
	ReleaseHandle(m_hConnect);
	ReleaseHandle(m_hSession);
}

// 释放句柄 [3/14/2017/shike]
void CWininetHttp::ReleaseHandle(HINTERNET& hInternet)
{
	if (hInternet)
	{
		InternetCloseHandle(hInternet);
		hInternet = NULL;
	}
}

// UTF-8转为GBK2312 [3/14/2017/shike]
char* CWininetHttp::UtfToGbk(const char* utf8)
{
	int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
	wchar_t* wstr = new wchar_t[len + 1];
	memset(wstr, 0, len + 1);
	MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr, len);
	len = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);
	char* str = new char[len + 1];
	memset(str, 0, len + 1);
	WideCharToMultiByte(CP_ACP, 0, wstr, -1, str, len, NULL, NULL);
	if (wstr) delete[] wstr;
	return str;
}

main.cpp文件

#include <iostream>
#include <stdio.h>
#include <string>
#include <map>
#include <thread>
#include "../WininetHttp.h"


int main()
{
	//测试http请求
	CWininetHttp whttp = CWininetHttp();
	string url = "http://tingapi.ting.baidu.com/v1/restserver/ting?format=json&callback=&from=webapp_music&method=baidu.ting.billboard.billList&type=1&size=10&offset=0";
	string json = whttp.RequestJsonInfo(url, Hr_Get, "", "");
	cout << "返回json" << json << endl; return0;}


本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

c++ http请求,json解析 的相关文章

随机推荐

  • python中使用subprocess.Popen中的返回值总结:

    usr bin python coding UTF 8 import sys import subprocess import traceback author by zhangheng timestamp 2018 06 08 gennl
  • SPI工作模式

    1 SPI总线条数 MISO xff1a 主设备输入 从设备输出引脚 该引脚在从模式下发送数据 xff0c 在主模式下接收数据 MOSI xff1a 主设备输出 从设备输入引脚 该引脚在主模式下发送数据 xff0c 在从模式下接收数据 SC
  • 游戏常用算法:四种迷宫生成算法

    简介 所谓迷宫生成算法 xff0c 就是用以生成随机的迷宫的算法 迷宫生成算法是处于这样一个场景 xff1a 一个row行 xff0c col列的网格地图 xff0c 一开始默认所有网格四周的墙是封闭的 要求在网格地图边缘 xff0c 也就
  • OPEN alliance工作小组

    Open Alliance TC 8小组 TC 8 xff1a 汽车以太网ECU测试规范 TC 8分配了汽车以太网ECU测试规范 它根据这些共享要求定义了适用于汽车以太网网络中所有ECU的规范 TC8定义了测试流程和支持建立能够执行ECU测
  • 测试PCB线路的阻抗的方法

    1 TDR测试 TDR是利用短脉冲信号发送到测试信号线上 xff0c 当信号到达另一端或者遇到不匹配点的时候就会发生反射回来 通过测量反射信号的时间和特征来判断线路的阻抗和不匹配点的位置 TDR测试需要专业的测试设备 xff0c 如时域反射
  • 开关电源的特性阻抗

    一 开关电源的特性阻抗好坏可以用以下几个量化指标来评估 xff1a 1 交流阻抗 xff08 AC Impedance xff09 xff1a 交流阻抗是指开关电源在交流信号下的电阻 电感和电容等电学特性 交流阻抗的好坏直接影响开关电源的驱
  • 学网络比不可少的网络协议分析神器-wireshark

    Wireshark是一款网络协议分析器 xff0c 可以用于捕获和分析网络数据包 xff0c 以便深入了解网络通信的细节和性能 xff0c 同时也可以用于网络安全分析和故障排除 Wireshark的主要功能包括 xff1a 1 捕获网络数据
  • C语言return的用法详解,C语言函数返回值详解

    C语言return的用法详解 xff0c C语言函数返回值详解 函数的返回值是指函数被调用之后 xff0c 执行函数体中的代码所得到的结果 xff0c 这个结果通过 return 语句返回 return 语句的一般形式为 xff1a spa
  • 网络编程——多线程编程

    文章目录 目的内容源代码及结果 1 Linux下的线程同步 1 1 编程使用互斥量实现线程同步 xff1b 1 2 编程使用信号量实现线程同步 xff0c 要求实现以下功能 xff1a 线程A从用户输入得到值后存入全局变量num xff0c
  • ARM-MPU内存保护单元详解

    ARM MPU 详解 简介 MPU Memory Protection Unit 内存保护单元 本文主要讲 armv7 m 架构 架构下的 MPU 在 armv7 m 架构下 xff0c Cortex M3 和 Cortex M4 处理器对
  • 玩转doxygen 之RT-THREAD

    玩转doxygen 之RT THREAD 文章目标 经常会看到小伙伴们遇到怎么写函数注释头疼 xff0c 以及如何生成漂亮的代码注释文档头疼 据我了解 xff0c 目前C语言中的代码注释规则有且只有一种比较常用 xff0c 就是doxyge
  • STM32如何将文件放到内部flash里面

    STM32如何将文件放到内部flash里面 背景介绍 上一篇讲到如何将STM32的FLASH改成文件系统 xff1a 如何不用外设在STM32片上FLASH做一个文件系统 https club rt thread org ask artic
  • 营运型手游开发、测试、正式的三阶段开发架构

    在手机游戏的畅销排行榜上 xff0c 可以看到大多数的游戏都是营运型的游戏 所谓的营运型游戏 xff0c 指的是游戏的开发并不是上架后就结束 xff0c 而是需要持续的配合游戏营运的需求 xff0c 进行游戏的更新 内容调整以及后续内容的开
  • 【github】【action】如何给软件包添加CI集成

    github action 如何给软件包添加CI集成 简介 github有自己的CI集成工具 action 很少有小伙伴关注到 xff0c 如果你有自己的软件包 xff0c 想要对其进行维护的话 xff0c 添加CI集成能够方便你快速验证你
  • Access 标准表达式中数据类型不匹配

    Access 标准表达式中数据类型不匹配 Access标准表达式中数据类型不匹配 今天在做一个小程序时 要求用到Access数据库 在调试运行一个SELECT语句时 老是提示标准表达式中数据类型不匹配 弄了好久 原来发现是数据类型不匹配的问
  • c#中new一个对象以后,是否需要手动释放?

    c 中new一个对象以后 xff0c 是否需要手动释放 xff1f 2012 04 28 23 43 wshbfzdzb 分类 xff1a C NET 浏览723次 c 43 43 中 class1 a 61 new class1 需要在用
  • ARM M0+各种定时器驱动的编写

    systick 系统滴答时间 这个定时器之前的文章已经讲过 这个是一个递减的定时器 xff0c 有个模数寄存器 在此不多说 就是一个系统的模块 xff0c 这个模块是集成在ARM M0 43 内核中的 xff0c 其实主要是集成在NVIC
  • MG323所有命令使用

    AT 43 CGMR 61 OK AT 43 GMR 61 OK AT 43 GMR 12 210 10 05 00 OK AT 43 CGSN 351869042318140 OK AT 43 CIMI 460021734971641 O
  • BAT文件的常用语法

    bat文件中常用的命令有 xff1a echo 64 rem pause goto call if copy等 下面简要给出这几个命令的用法 1 echo命令 echo 表示显示此命令后的字符 例如echoHello World choHe
  • c++ http请求,json解析

    一 文章内容 解决c 43 43 http请求以及对返回结果json串进行解析 xff0c 使用jsoncpp库 二 安装jsoncpp插件 vs2015通过NuGet直接安装jsoncpp到项目下 安装好之后 xff0c 会在项目下有个p