本例以访问
https://zh.arslanbar.net/API/为例。
【C++代码】
// HTTP.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <Winhttp.h>
#pragma comment(lib, "Winhttp.lib")
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
HINTERNET hSession = WinHttpOpen(L"A WinHTTP Example Program/1.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, NULL);
if (hSession)
{
HINTERNET hConnect = WinHttpConnect(hSession, L"zh.arslanbar.net", INTERNET_DEFAULT_HTTP_PORT, NULL);
HINTERNET hRequest = WinHttpOpenRequest(hConnect, NULL, L"API", NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_REFRESH);
BOOL bResult = WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, NULL, WINHTTP_NO_REQUEST_DATA, NULL, NULL, NULL);
if (!bResult)
cout << "Error " << GetLastError() << " has occurred." << endl;
WinHttpReceiveResponse(hRequest, NULL);
DWORD dwSize;
bResult = WinHttpQueryDataAvailable(hRequest, &dwSize);
if (bResult)
{
DWORD dwDownloaded = 0;
char *data = new char[dwSize + 1];
WinHttpReadData(hRequest, data, dwSize, &dwDownloaded);
data[dwSize] = '\0';
cout << "dwSize = " << dwSize << endl;
cout << data << endl;
delete[] data;
}
else
{
DWORD dwError = GetLastError();
cout << "Error " << dwError << " in WinHttpQueryDataAvailable." << endl;
if (dwError == ERROR_WINHTTP_INCORRECT_HANDLE_STATE)
cout << "The requested operation cannot complete because the handle supplied is not in the correct state." << endl;
}
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
}
else
cout << "Error " << GetLastError() << " in WinHttpOpen." << endl;
WinHttpCloseHandle(hSession);
system("pause");
return 0;
}
【运行结果】
dwSize = 12
No Operation