123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- #include "publicFunExport.h"
- #include <stdio.h>
- #include <string>
- #if (defined _WIN32 || defined _WIN64)
- #include <winsock.h>
- #pragma comment(lib,"Ws2_32.lib")
- #include "Wininet.h"
- #pragma comment(lib,"Wininet.lib")
- #else
- #include <requests/Exception.hpp>
- #include <requests/Request.hpp>
- #include <requests/Url.hpp>
- #endif
- #if (defined _WIN32 || defined _WIN64)
- bool checkHttpActive(const char* httpUrl)
- {
- TCHAR szHostName[128];
- TCHAR szUrlPath[256];
- URL_COMPONENTS crackedURL = { 0 };
- crackedURL.dwStructSize = sizeof(URL_COMPONENTS);
- crackedURL.lpszHostName = szHostName;
- crackedURL.dwHostNameLength = ARRAYSIZE(szHostName);
- crackedURL.lpszUrlPath = szUrlPath;
- crackedURL.dwUrlPathLength = ARRAYSIZE(szUrlPath);
- InternetCrackUrl(httpUrl, (DWORD)strlen(httpUrl), 0, &crackedURL);
- HINTERNET hInternet = InternetOpen("Microsoft InternetExplorer", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
- if (hInternet == NULL)
- return false;
- HINTERNET hHttpSession = InternetConnect(hInternet, crackedURL.lpszHostName, crackedURL.nPort, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
- if (hHttpSession == NULL)
- {
- InternetCloseHandle(hInternet);
- return false;
- }
- HINTERNET hHttpRequest = HttpOpenRequest(hHttpSession, "GET", crackedURL.lpszUrlPath, NULL, "", NULL, 0, 0);
- if (hHttpRequest == NULL)
- {
- InternetCloseHandle(hHttpSession);
- InternetCloseHandle(hInternet);
- return false;
- }
- /**
- * 查询http状态码(这一步不是必须的),但是HttpSendRequest()必须要调用
- */
- DWORD dwRetCode = 0;
- DWORD dwSizeOfRq = sizeof(DWORD);
- if (!HttpSendRequest(hHttpRequest, NULL, 0, NULL, 0) ||
- !HttpQueryInfo(hHttpRequest, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &dwRetCode, &dwSizeOfRq, NULL)
- || dwRetCode >= 400)
- {
- InternetCloseHandle(hHttpRequest);
- InternetCloseHandle(hHttpSession);
- InternetCloseHandle(hInternet);
- return false;
- }
- InternetCloseHandle(hHttpRequest);
- InternetCloseHandle(hHttpSession);
- return true;
- }
- #else
- bool checkHttpActive(const char* httpUrl)
- {
- requests::Request request;
- requests::Url url(httpUrl);
- try
- {
- // 发起 HTTP 请求,阻塞
- auto resp = request.get(url);
- return true;
- }
- catch (requests::Exception& e)
- {
- std::cout << e.what() << std::endl;
- }
- return false;
- }
- #endif
|