使用Windows API发送HTTP(S)请求
发布时间:2020-12-14 02:32:17 所属栏目:Windows 来源:网络整理
导读:先看一个简单的GET示例 #include Windows.h #include winhttp.h #include stdio.h int main(){ HINTERNET sessionHandle = WinHttpOpen(L " WinHttp Example " ,WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,WINHTTP_NO_PROXY_NAME,WINHTTP_NO_PROXY_BYPASS, 0 ); if
先看一个简单的GET示例 #include <Windows.h> #include <winhttp.h> #include <stdio.h> int main() { HINTERNET sessionHandle = WinHttpOpen(L"WinHttp Example",WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,WINHTTP_NO_PROXY_NAME,WINHTTP_NO_PROXY_BYPASS,0); if (sessionHandle) { HINTERNET connectionHandle = WinHttpConnect(sessionHandle,L"example.com",INTERNET_DEFAULT_HTTP_PORT,0); if (connectionHandle) { HINTERNET requestHandle = WinHttpOpenRequest(connectionHandle,L"GET",L"",NULL,WINHTTP_NO_REFERER,WINHTTP_DEFAULT_ACCEPT_TYPES,0); if (requestHandle) { BOOL success = WinHttpSendRequest(requestHandle,WINHTTP_NO_ADDITIONAL_HEADERS,0,WINHTTP_NO_REQUEST_DATA,0); if (success) { success = WinHttpReceiveResponse(requestHandle,NULL); if (success) { DWORD dwSize; do { dwSize = 0; LPSTR pszOutBuffer; DWORD dwDownloaded = 0; if (!WinHttpQueryDataAvailable(requestHandle,&dwSize)) { printf("Error %u in WinHttpQueryDataAvailable.n",GetLastError()); break; } // No more available data. if (!dwSize) break; // Allocate space for the buffer. pszOutBuffer = new char[dwSize + 1]; if (!pszOutBuffer) { printf("Out of memoryn"); break; } // Read the Data. ZeroMemory(pszOutBuffer,dwSize + 1); if (!WinHttpReadData(requestHandle,(LPVOID)pszOutBuffer,dwSize,&dwDownloaded)) { printf("Error %u in WinHttpReadData.n",GetLastError()); } else { printf("%s",pszOutBuffer); } // Free the memory allocated to the buffer. delete[] pszOutBuffer; // This condition should never be reached since WinHttpQueryDataAvailable // reported that there are bits to read. if (!dwDownloaded) break; } while (dwSize > 0); } else { // Report any errors. printf("Error %d has occurred.n",GetLastError()); } } else { printf("Request failedn"); } WinHttpCloseHandle(requestHandle); } else { printf("Invalid request handlen"); } WinHttpCloseHandle(connectionHandle); } else { printf("Invalid connection handlen"); } WinHttpCloseHandle(sessionHandle); } else { printf("Invalid WinHTTP-session handlen"); } system("pause"); return 0; } 有没有一种要崩溃的节奏 更麻烦的不是代码量的问题,而是这些API暴露了太多的细节(当然,暴露细节的好处是不限制开发员的思想,根据需求灵活编码)。很多时候,我们并不需要考虑那么多的细节 试着封装成C++类的形式,然而我放弃了,真的太麻烦了 参考链接:WinHttpReadData function | Microsoft Docs (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- windows环境 springboot+docker开发环境搭建与he
- windows-server-2008 – 无法在KVM上安装Win2k8
- 方便的Windows相当于tail -f logfile?
- Win常用软件
- windows-server-2012 – 如何在Windows Server 2
- Windows BAT或CMD:将一些数据发送到localhost u
- .net – PowerShell中的echo和Write-Host有什么区
- windows-8 – 在Visual Studio 2015中构建Window
- 通过cmd 使用 InstallUtil.exe 命令 操作 window
- Symfony的最佳分步教程(我在Windows上运行PHP)
热点阅读