WininetHttp.h
#pragma once
#include <iostream>
#include <windows.h>
#include <wininet.h>
#include <map>
#include <functional>
using namespace std;
//每次讀取的字節(jié)數(shù)
#define READ_BUFFER_SIZE 4096
enum HttpInterfaceError
{
Hir_Success = 0, //成功
Hir_InitErr, //初始化失敗
Hir_ConnectErr, //連接HTTP服務(wù)器失敗
Hir_SendErr, //發(fā)送請求失敗
Hir_QueryErr, //查詢HTTP請求頭失敗
Hir_404, //頁面不存在
Hir_IllegalUrl, //無效的URL
Hir_CreateFileErr, //創(chuàng)建文件失敗
Hir_DownloadErr, //下載失敗
Hir_QueryIPErr, //獲取域名對應(yīng)的地址失敗
Hir_SocketErr, //套接字錯誤
Hir_UserCancel, //用戶取消下載
Hir_BufferErr, //文件太大烘苹,緩沖區(qū)不足
Hir_HeaderErr, //HTTP請求頭錯誤
Hir_ParamErr, //參數(shù)錯誤,空指針,空字符
Hir_UnknowErr,
};
enum HttpRequest
{
Hr_Get,
Hr_Post
};
class CWininetHttp
{
public:
//單例模式
static CWininetHttp& getInstance()
{
static CWininetHttp m_winHttp;
return m_winHttp;
}
CWininetHttp(const CWininetHttp&) = delete;
CWininetHttp& operator =(const CWininetHttp&) = delete;
~CWininetHttp(void);
//同步獲取http請求
string synRequestInfo(const string& lpUrl, HttpRequest type, map<string, string> param = map<string, string>());
//異步獲取http請求
void asynRequestInfo(const string& lpUrl, HttpRequest type, map<string, string> param, std::function<void(string)> callBack);
private:
CWininetHttp(void);
// 通過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 = "");
string getUrl(const string& lpUrl, map<string, string> param);
void asynRequestThread(string totalUrl, HttpRequest type);
// 關(guān)閉句柄
void Release();
// 釋放句柄
void ReleaseHandle(HINTERNET& hInternet);
// 解析URL地址
void ParseURLWeb(std::string strUrl, std::string& strHostName, std::string& strPageName, WORD& sPort);
// UTF-8轉(zhuǎn)為GBK2312
char* UtfToGbk(const char* utf8);
private:
HINTERNET m_hSession;
HINTERNET m_hConnect;
HINTERNET m_hRequest;
HttpInterfaceError m_error;
std::function<void(string)> callBack = NULL;
};
WininetHttp.cpp
//#include "stdafx.h"
#include "WininetHttp.h"
#include <fstream>
#pragma comment(lib, "Wininet.lib")
#include <tchar.h>
#include <thread>
CWininetHttp::CWininetHttp(void) :m_hSession(NULL), m_hConnect(NULL), m_hRequest(NULL)
{
}
CWininetHttp::~CWininetHttp(void)
{
Release();
}
//同步請求
string CWininetHttp::synRequestInfo(const string& lpUrl, HttpRequest type, map<string, string> param)
{
string totalUrl = getUrl(lpUrl, param);
return RequestJsonInfo(totalUrl, type);
}
//異步請求線程
void CWininetHttp::asynRequestThread(string totalUrl, HttpRequest type)
{
string jsonStr = RequestJsonInfo(totalUrl, type);
if (callBack != NULL)
callBack(jsonStr);
}
//異步請求
void CWininetHttp::asynRequestInfo(const string& lpUrl, HttpRequest type, map<string, string> param, std::function<void(string)> callBack)
{
this->callBack = callBack;
string totalUrl = getUrl(lpUrl, param);
thread t(&CWininetHttp::asynRequestThread, this, totalUrl, type);
t.detach();
}
//拼接地址
string CWininetHttp::getUrl(const string& lpUrl, map<string, string> param) {
string paramstr = "";
string totalUrl = lpUrl;
for (map<string, string>::iterator ite = param.begin(); ite != param.end(); ite++)
{
paramstr += ite->first + "=" + ite->second + "&";
}
if (paramstr.length() > 0)
{
paramstr = paramstr.substr(0, paramstr.length() - 1);
totalUrl = lpUrl + "?" + paramstr;
}
return totalUrl;
}
/*
lpUrl:url地址,如 http://127.0.0.1:8081/hello?name=csy ,其中?后為參數(shù)
type:請求類型 get or post
strHeader:可增添頭部豁鲤,一般為空
strPostData:post請求參數(shù)猛们,但是這里好像不生效,可統(tǒng)一將參數(shù)拼接到lpUrl中
*/
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;
}
strRet = UtfToGbk(strRet.c_str());
return strRet;
}
// 解析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);
}
void CWininetHttp::Release()
{
ReleaseHandle(m_hRequest);
ReleaseHandle(m_hConnect);
ReleaseHandle(m_hSession);
}
void CWininetHttp::ReleaseHandle(HINTERNET& hInternet)
{
if (hInternet)
{
InternetCloseHandle(hInternet);
hInternet = NULL;
}
}
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 "WininetHttp.h"
#include <iostream>
#include <sstream>
#include "json11.h" // 庫的github 地址 https://github.com/dropbox/json11/tree/master
#include <map>
using namespace json11;
int main()
{
std::cout << "Hello World!\n";
map<string, string> param;
param.insert(pair<string, string>("sbId", "98"));
//1典挑、同步調(diào)用
string jsonStr = CWininetHttp::getInstance().synRequestInfo("http://127.0.0.1:8081/api/front/banner/groupBanner", Hr_Get, param);
std::cout << jsonStr << "\n";;
string err;
const auto json = Json::parse(jsonStr, err);
std::cout << "code: " << json["code"].int_value() << "\n";
std::cout << "message: " << json["message"].string_value() << "\n";
std::cout << "data: " << json["data"].is_null() << "\n";
}
int main()
{
std::cout << "Hello World!\n";
map<string, string> param;
param.insert(pair<string, string>("sbId", "98"));
//1、同步調(diào)用
string jsonStr = CWininetHttp::getInstance().synRequestInfo("http://127.0.0.1:8081/api/front/banner/groupBanner", Hr_Get, param);
std::cout << jsonStr << "\n";;
string err;
const auto json = Json::parse(jsonStr, err);
std::cout << "code: " << json["code"].int_value() << "\n";
std::cout << "data: " << json["data"].string_value() << "\n";
}
請求結(jié)果
image.png