当前位置: 首页 > 编程日记 > 正文

C++通过HTTP请求Get或Post方式请求Json数据(转)

原文网址: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;
}

转载于:https://www.cnblogs.com/Pond-ZZC/p/9529019.html

相关文章:

工厂模式 android,当Android遇见工厂模式

设计模式.png我们先看一下一个Android系统应用中的工厂模式列子&#xff0c;再讲解工厂模式。package com.android.mms.ui;import android.content.Context;import android.util.Log;import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException…

抽象工厂模式 java实例 tclhaier_Unity常用的设计模式_工厂模式系列之抽象工厂模式...

在工厂方法模式中&#xff0c;工厂只负责生产具体的产品&#xff0c;每一个具体的工厂对应着一个具体的产品&#xff0c;工厂方法也具有唯一性&#xff0c;如果有时候我们需要一个工厂方法提供多个产品而不是一个单一的产品&#xff0c;例如&#xff1a;海尔品牌不止生产海尔TV…

npm-run 自动化

为什么使用npm run 插件不需要全局安装&#xff0c;只要安装在工程项目中&#xff0c;npm上的包提供了命令行接口&#xff0c;可以直接使用这些局部安装的插件; 举例&#xff08;babel&#xff09;&#xff1a; 在工程项目中局部安装babel、转码规则后&#xff0c;直接在终端中…

docker 安装 oracle12,使用Docker安装Oracle 12c

使用Docker安装Oracle 12c假设你的服务器已成功安装Docker&#xff0c;继续进行以下操作&#xff1a;1. 启动Docker[rootnode01 ~]# service docker start2. 从远程仓库搜索oracle image[rootnode01 ~]# docker search oracleINDEX NAME DESCRIPTION STARS OFFICIAL AUTOMATEDd…

python3 面向对象(一)

以Student类为例&#xff0c;定义类通过 class 关键字 class Student(object):pass class 后面紧接着是类名&#xff0c;即 Student&#xff0c;类名通常是大写开头的单词&#xff0c;紧接着是 (object)&#xff0c;表示该类是从哪个类继承下来的 >>> stu Student() …

shell监控java接口服务_Linux系统下Java通过shell脚本监控重启服务

简介最近运维人员提出需求&#xff0c;增加一个运维页面&#xff0c; 查询当前的业务进程信息包括&#xff1a;进程名称、启动命令、启动时间、运行时间等&#xff0c;可以通过页面点击重启按钮&#xff0c;可以重启后端的一系列系统进程。思路java程序获取linux进程信息可以通…

signature=680da11b802226668317d65ae7c38eb7,encryption with designated verifiers

摘要&#xff1a;The offline keyword guessing attack (KG attack) is a new security threat to the searchable public key encryption with designated verifier. Many techniques have been proposed to resist such an attack. However, all these techniques are only s…

PHPMailer类 发送邮件

/*** [sendMail 邮件发送类]* param [string] $address [收件人的邮件地址]* param [string] $nickname [收件人的昵称]* param [string] $subject [邮件的标题]* param [string] $content [邮件的内容]* param [string] $attachment [邮件的附件]* return …

oracle两张表 比较好,比较Oracle两张表的数据是否一样

比较Oracle两张表的数据是否一样爱搞机 2008-10-21 11:00在某些情况下&#xff0c;我们会需要比较两张表的数据是否一样。假设有两张表A与表B他的字段相同&#xff0c;但是当中的数据可能不同&#xff0c;而且有些字段的数据还有可能为空方法一(手动)&#xff1a;把需要比较的两…

java applet 缺陷_Java Applet在最新JRE上的奇怪性能行为(7.55)

我们使用来自签名提供商的一些专有小程序来签署一些XML.当我们使用JRE 6u37 applet运行没有问题 – 运行速度非常快,从不冻结.但是当我们将JRE更新为7u55或更新时,它经常开始挂起.只有浏览器重启帮助.有没有办法解决这个问题可能是由一些参数或其他东西&#xff1f;这是运行代码…

在线考试系统html模板,请问谁有在线考试系统的网页模板?

请问谁有在线考试系统的网页模板&#xff1f;(2017-03-22 22:58:03)标签&#xff1a;杂谈《帝国网站管理系统》英文译为"EmpireCMS"&#xff0c;简称"Ecms"&#xff0c;它是基于B/S结构&#xff0c;且功能强大而帝国CMS-logo易用的网站管理系统。本系统由帝…

三角形(css3)

1 .userCard .sanjiao {//三角形的制作&#xff1b;2 width: 0;3 height: 0;4 border-left: 10px solid transparent;5 border-right: 10px solid transparent;6 border-bottom: 10px solid rgba(0, 0, 0, .9);7 margin: -23px 0 0 -10px;8 left: …

MySQL数据copy

摘自http://database.51cto.com/art/201011/234776.htm 1. 下面这个语句会拷贝表结构到新表newadmin中。 &#xff08;不会拷贝表中的数据&#xff09; CREATE TABLE newadmin LIKE admin 2. 下面这个语句会拷贝数据到新表中。 注意&#xff1a;这个语句其实只是把select语句…

oracle数据库有哪些文件构成,Oracle数据库架构中包括几层?每层都有什么元素?...

Oracle数据库架构中包括几层&#xff1f;每层都有什么元素&#xff1f;1 PL/SQL代表 A PROCEDURAL LANGUAGE/SQL B PROGRAM LANGUAGE SQL C POWER LANGUAGE SQL D 都不对2 _____引擎执行PL/SQL块A SQL B PL/SQL C ORACLE D 都不对3 一个对象可以呈现多种形式的能力称为A 多态B …

用html怎么 显示直线,html怎么用鼠标画出一条直线,鼠标移动时候要能看到线条...

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼window.onload function(){var oC document.getElementById(c1);var oGC oC.getContext(2d);oC.onmousedown function(ev){var ev ev || window.event;oGC.beginPath();oGC.moveTo(ev.clientX-oC.offsetLeft,ev.clientY-oC.of…

bzoj 1962: 模型王子

呵呵呵呵http://wenku.baidu.com/link?urlo0CPVzuBDLJMt0_7Qph1T7TtdFOzu7O-apIpvaWbIYMz8ZWqBneGqI8LGtLdqpuK5fbQ_v-H01zHwPXDsPrioR5xjCDHjqJn_boYO87ikr_ 1 #include <bits/stdc.h>2 #define LL long long3 #define lowbit(x) x&(-x)4 #define inf 0x3f3f3f3f5 …

cygwin编译verilator_Windows 安装 verilator

windows bubun(cygwin)下载verilatortar xvzf verilator*.t*gzcd verilator*./configure报错./configure /cygdrive/e/download/verilator-4.016configuring for Verilator 4.016 2019-06-16checking whether to use hardcoded paths... yeschecking whether to show and stop …

navicat 几个 可用的东西

1.常用的 表格 一启动 就进入的某某连接某某数据库某某表 2. 结构 比对&#xff08;菜单栏 “工具里面”&#xff09; 3.数据对比 同上 4.保持连接 5.全局查询 在工具中查找 ------在数据库或模式中查找 转载于:https://www.cnblogs.com/hnqm/p/9534942.html

linux内核 semaphore,2.4内核里semaphore源码的一个疑问

博主你好, 请教一个问题.__down()里面有一段代码, 我觉得不那么保险.我先把__down的源码贴出来:void __down(struct semaphore * sem){struct task_struct *tsk current;DECLARE_WAITQUEUE(wait, tsk); //定义一个"队列项", 等待者是当前进…

Android UI体验之全屏沉浸式透明状态栏效果

前言&#xff1a; Android 4.4之后谷歌提供了沉浸式全屏体验&#xff0c; 在沉浸式全屏模式下&#xff0c; 状态栏、 虚拟按键动态隐藏&#xff0c; 应用可以使用完整的屏幕空间&#xff0c; 按照 Google 的说法&#xff0c; 给用户一种 身临其境 的体验。而Android 5.0之后谷歌…

html 多项选择,选项标签中的HTML多字段选择

这可以通过switch语句实现&#xff0c;但这不是最好的方法。我建议将以下函数作为change事件的事件处理程序。您还需要在窗口加载时运行它&#xff0c;以初始化它。function updateSel() {var sel document.getElementById(sel);var hidden sel.getElementsByClassName(hidde…

tp5.0 queue 队列操作

检查是否安装redis(没有请自行百度安装)&#xff1a; phpinfo&#xff1a; 配置thinkphp-queue&#xff0c;没有请执行 composer require topthink/think-queue 加入&#xff1a; 创建 队列 文件&#xff1a; use think\Queue;class TestQueue {// 测试public function queue()…

java redis管理_优雅时间管理Java轻松做到,想学么?

原标题&#xff1a;优雅时间管理Java轻松做到&#xff0c;想学么&#xff1f;来源 |http://rrd.me/gCQHp前言&#xff1a;需求是这样的&#xff0c;在与第三方对接过程中&#xff0c;对方提供了token进行时效性验证&#xff0c;过一段时间token就会失效.后台有定时任务在获取&a…

jenkins运行日志时间与linux,Jenkins 用户文档(运行多个步骤)

运行多个步骤管道由多个步骤组成&#xff0c;允许你构建、测试和部署应用程序&#xff0c;Jenkins管道允许你以简单的方式组成多个步骤&#xff0c;可以帮助你为任何类型的自动化过程建模。将“步骤”想象成执行单个操作的单个命令&#xff0c;当一个步骤成功时&#xff0c;它将…

HPU组队赛B:问题(二进制枚举)

时间限制1 Second 内存限制 512 Mb 题目描述 你有n个问题&#xff0c;你已经估计了第i个问题的难度为Ci,现在你想使用这些问题去构造一个问题集。比赛的问题集必须包含至少两个问题&#xff0c;而且比赛的总难度必须至少为l至多为r,此外最简单的问题和最难的问题之间的差异至少…

html脱机不显示图片,Python绘图脱机图表嵌入HTML(不工作)

aPlot是绘图文件的文件名。在在您的iframe中&#xff0c;您将.embed?width800&height550添加到文件名中&#xff0c;这将导致一个不存在的文件名。在当您删除这个字符串时&#xff0c;即src" aPlot "&#xff0c;它应该可以工作。在不必嵌入整个HTML文件&…

数据库分库分表(sharding)系列

数据库分库分表(sharding)系列转载于:https://www.cnblogs.com/gotodsp/p/6517478.html

php imagecopy 用法,php使用imagecopymerge()函数创建半透明水印

使用imagecopymerge() 函数创建半透明水印&#xff0c;供大家参考&#xff0c;具体内容如下// 加载要加水印的图像$im imagecreatefromjpeg(photo.jpeg);// 首先我们从 GD 手动创建水印图像$stamp imagecreatetruecolor(100, 70);imagefilledrectangle($stamp, 0, 0, 99, 69,…

linux系统yum源,Linux开启安装EPEL YUM源

我们用yum安装软件时,经常发现我们的yum源里面没有该软件&#xff0c;需要自己去wget&#xff0c;然后configure,make,make install&#xff0c;太折腾了。其实&#xff0c;CentOS还有一个源叫做 EPEL (Extra Packages for Enterprise)&#xff0c;里面有1万多个软件&#xff0…

MATLAB简易验证码识别程序介绍

本推文主要识别的验证码是这种:第一步: 二值化所谓二值化就是把不需要的信息通通去除&#xff0c;比如背景&#xff0c;干扰线&#xff0c;干扰像素等等&#xff0c;只剩下需要识别的文字&#xff0c;让图片变成2进制点阵。第二步: 文字分割为了能识别出字符&#xff0c;需要对…