1. 程式人生 > >使用Windows API發送HTTP(S)請求

使用Windows API發送HTTP(S)請求

\n val ref reported col 很多 print condition hand

先看一個簡單的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, 0, 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 memory\n"); 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 failed\n"); } WinHttpCloseHandle(requestHandle); } else { printf("Invalid request handle\n"); } WinHttpCloseHandle(connectionHandle); } else { printf("Invalid connection handle\n"); } WinHttpCloseHandle(sessionHandle); } else { printf("Invalid WinHTTP-session handle\n"); } system("pause"); return 0; }

有沒有一種要崩潰的節奏技術分享圖片僅從example.com獲取網頁代碼,就要寫約90行的代碼

更麻煩的不是代碼量的問題,而是這些API暴露了太多的細節(當然,暴露細節的好處是不限制開發員的思想,根據需求靈活編碼)。很多時候,我們並不需要考慮那麽多的細節

試著封裝成C++類的形式,然而我放棄了,真的太麻煩了技術分享圖片還是用libcurl或cpr之類的庫吧

參考鏈接:WinHttpReadData function | Microsoft Docs

使用Windows API發送HTTP(S)請求