原文网址:https://www.cnblogs.com/shike8080/articles/6549339.html

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

/*************************************************
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 "Common.h"
//#include <json/json.h>
#include <fstream>
//#include "common/CVLog.h"
#pragma comment(lib, "Wininet.lib")
#include <tchar.h>
using namespace std;

extern CCVLog CVLog;

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))
// {
// CVLog.LogMessage(LOG_LEVEL_ERROR,"[CXLDbDataMgr::GetVideoGisData] Video Gis parse data 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;
}

C++通过HTTP请求Get或Post方式请求Json数据(转)的更多相关文章

  1. 前端ajax用post方式提交json数据给后端时,网络报错 415

    项目框架:spring+springmvc+mybatis 问题描述:前端ajax用post方式提交json数据给后端时,网络报错 415 前端异常信息:Failed to load resource ...

  2. J2EE Web开发入门—通过action是以传统方式返回JSON数据

    关键字:maven.m2eclipse.JSON.Struts2.Log4j2.tomcat.jdk7.Config Browser Plugin Created by Bob 20131031 l ...

  3. 导出excel时,以form方式提交json数据

    今天在写项目时写到一个excel的导出,开始想用ajax请求后台后导出,但发现ajax会有返回值,而且ajax无法直接输出文件,而后台的excel导出方法已经封装好,不方便修改. 就改用了提交的方式f ...

  4. 基于Web Service的客户端框架搭建一:C#使用Http Post方式传递Json数据字符串调用Web Service

    引言 前段时间一直在做一个ERP系统,随着系统功能的完善,客户端(CS模式)变得越来越臃肿.现在想将业务逻辑层以下部分和界面层分离,使用Web Service来做.由于C#中通过直接添加引用的方来调用 ...

  5. 使用Ajax方式POST JSON数据包(转)

    add by zhj: 用ajax发送json数据时注意两点, 第一,使用JSON.stringify()函数将data转为json格式的字符串,如下 data: JSON.stringify({   ...

  6. 前端学习——使用Ajax方式POST JSON数据包

    0.前言     本文解释怎样使用Jquery中的ajax方法传递JSON数据包,传递的方法使用POST(当然PUT又有时也是一个不错的选择).POST JSON数据包相比标准的POST格式可读性更好 ...

  7. vue-cli项目 build后请求本地static文件中的 json数据,路径不对,报错404处理方法

    vue-cli 项目 build  出错点: 1,build生成dist 放在tomcat上 报错,不显示内容  解决办法: config>index.js===>assetsPublic ...

  8. django 使用Ajax方式POST JSON数据包

    示例1: js: function SaveAction(){ //点击 保存按键 var senddata = {"type":"A", "host ...

  9. phpStudy4——前端页面使用Ajax请求并解析php返回的json数据

    项目需求: 在html页面显示所有用户列表信息. 需求分析: 1. html页面使用ajax向后端php请求用户数据 2. php脚本查询数据库,并将查询后的结果以json格式返回前端html页面 3 ...

随机推荐

  1. python基础之3

    1,列表可以嵌套任何东西.包括字典,列表等 字典是无序的健值型,不需要下标,也可以嵌套列表和字典 2,集合:对列表进行差异化处理后形成集合,特点:去重和无序.主要作用: (1)去重;(2) 关系测试, ...

  2. 参数估计(1):从最小二乘到最小b乘

    机器学习到底学习到了什么,或者说“训练”步骤到底在做些什么?在我看来答案无非是:所谓的“学习”就是把大量的数据归纳到少数的参数中,“训练”正是估计这些参数的过程.所以,除了“参数估计”, 我想不到还有 ...

  3. CH5302 金字塔【区间DP】

    5302 金字塔 0x50「动态规划」例题 描述 虽然探索金字塔是极其老套的剧情,但是有一队探险家还是到了某金字塔脚下.经过多年的研究,科学家对这座金字塔的内部结构已经有所了解.首先,金字塔由若干房间 ...

  4. 解决Cell重绘导致 重复的问题

    IOS在Cell上的优化令人觉得底层框架的成熟,可是有些情形却会造成不必要的麻烦, 当使用了 UITableViewCell *cell = [tableView dequeueReusableCel ...

  5. Reference counted objects

    Reference counted objects · netty/netty Wiki https://github.com/netty/netty/wiki/Reference-counted-o ...

  6. The Personal Touch Client Identification 个性化接触 客户识别

    w服务器要知道和谁在交谈. HTTP The Definitive Guide Web servers may talk to thousands of different clients simul ...

  7. Tilera--100核cpu

    市场对多核的需求越来越多,主要是因为单核处理能力不可能像以往那样不断地提升.从上世纪90 年代开始,整个产业遵循摩尔定律,即芯片上可容纳的晶体管数目每隔18个月便会增加一倍,性能也提升一倍.随着时间的 ...

  8. python的@classmethod和@staticmethod

    本文是对StackOverflow上的一篇高赞回答的不完全翻译,原文链接:meaning-of-classmethod-and-staticmethod-for-beginner Python面向对象 ...

  9. 调试maven源代码

    下载源代码,导入idea 运行MavenCli ,设置vm参数 -Dclassworlds.conf=/Users/fsq/Downloads/apache-maven-3.6.2.0/bin/m2. ...

  10. Linux上安装MySQL及其基础配置

    本文主要介绍Linux下使用yum安装MySQL,以及启动.登录和远程访问MySQL数据库. 1.安装 查看有没有安装过: yum list installed mysql* rpm -qa | gr ...