C + + requests JSON data via HTTP request get or Post

Source: Internet
Author: User
Tags socket error

Original URL: https://www.cnblogs.com/shike8080/articles/6549339.html

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

using namespace Std;

Number of bytes per read
#define READ_BUFFER_SIZE 4096

Enum Httpinterfaceerror
{
hir_success = 0,//success
Hir_initerr,//initialization failed
Hir_connecterr,//connection to HTTP server failed
Hir_senderr,//Send request failed
Hir_queryerr,//query HTTP request header failed
hir_404,//page does not exist
Hir_illegalurl,//Invalid URL
Hir_createfileerr,//failed to create file
Hir_downloaderr,//download failed
Hir_queryiperr,//Failed to get the address corresponding to the domain name
Hir_socketerr,//Socket error
Hir_usercancel,//user cancel download
Hir_buffererr,//file too large, insufficient buffer
Hir_headererr,//http request header Error
Hir_paramerr,//parameter error, NULL pointer, null character
Hir_unknowerr,
};
Enum HttpRequest
{
Hr_get,
Hr_post
};
Class Cwininethttp
{
Public
Cwininethttp (void);
~cwininethttp (void);

Public
Get JSON information via HTTP request: Get or post [3/14/2017/shike]
Const std::string requestjsoninfo (const std::string& strURL,
HttpRequest type = Hr_get,
std::string Lpheader = "",
std::string lppostdata = "");
Protected
Parsing the bayonet JSON data [3/14/2017/shike]
void Parsejsoninfo (const std::string &strjsoninfo);

Close handle [3/14/2017/shike]
void Release ();

Release handle [3/14/2017/shike]
void ReleaseHandle (hinternet& hinternet);

Parse URL address [3/14/2017/shike]
void Parseurlweb (std::string strurl, std::string& strhostname, std::string& strpagename, WORD& sPort);

UTF-8 to 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: Get JSON through URL Access HTTP request method
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 ();
}

Get JSON information via HTTP request: Get or post [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); Local

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]= ' + ';
Strret.append (Szbuffer);
}
}
catch (httpinterfaceerror error)
{
M_error = error;
}
Return Std::move (strret);
}

Parsing JSON data [11/8/2016/shike]
void Cwininethttp::P arsejsoninfo (const std::string &strjsoninfo)
//{
Json::reader Reader; Parsing JSON with Json::reader
Json::value Value; can represent any type
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)//iterate over data array
// {
Pgcarddevdata Stru;
Stru.strcardname = value["Result"][npos]["Tollgatename"].asstring ();
Stru.strcardcode = value["Result"][npos]["Tollgatecode"].asstring ();
std::string strcdnum = value["Result"][npos]["Lanenumber"].asstring (); Increase: Total number of lanes
Stru.nlanenum = Atoi (Strcdnum.c_str ());
std::string Strlanedir = value["Result"][npos]["Lanedir"].asstring (); Added: Lane direction, rule conversion
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);
// }
// }
//}

Parse URL address [3/14/2017/shike]
void Cwininethttp::P arseurlweb (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)//not found
{
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);
}

Close handle [3/14/2017/shike]
void Cwininethttp::release ()
{
ReleaseHandle (m_hrequest);
ReleaseHandle (M_hconnect);
ReleaseHandle (m_hsession);
}

Release handle [3/14/2017/shike]
void Cwininethttp::releasehandle (hinternet& hinternet)
{
if (hinternet)
{
InternetCloseHandle (hinternet);
Hinternet = NULL;
}
}

UTF-8 to 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 + + requests JSON data via HTTP request get or post (GO)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.