MFC如何链接 http://169.254.1.10:8090/api/v1/~bali/ABC0123456789
时间: 2023-10-04 08:14:46 浏览: 140
MFC可以使用WinINet库中的函数来实现HTTP请求。以下是一个简单的示例代码:
```c++
#include <windows.h>
#include <wininet.h>
#pragma comment(lib, "wininet.lib")
int main()
{
HINTERNET hInternet = InternetOpen(L"Test", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
if (hInternet == NULL)
{
return 1;
}
HINTERNET hConnect = InternetConnect(hInternet, L"169.254.1.10", 8090, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
if (hConnect == NULL)
{
InternetCloseHandle(hInternet);
return 1;
}
HINTERNET hRequest = HttpOpenRequest(hConnect, L"GET", L"/api/v1/~bali/ABC0123456789", NULL, NULL, NULL, INTERNET_FLAG_RELOAD, 0);
if (hRequest == NULL)
{
InternetCloseHandle(hConnect);
InternetCloseHandle(hInternet);
return 1;
}
BOOL bSend = HttpSendRequest(hRequest, NULL, 0, NULL, 0);
if (!bSend)
{
InternetCloseHandle(hRequest);
InternetCloseHandle(hConnect);
InternetCloseHandle(hInternet);
return 1;
}
DWORD dwStatusCode = 0;
DWORD dwBufferLength = sizeof(dwStatusCode);
BOOL bQuery = HttpQueryInfo(hRequest, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &dwStatusCode, &dwBufferLength, NULL);
if (!bQuery)
{
InternetCloseHandle(hRequest);
InternetCloseHandle(hConnect);
InternetCloseHandle(hInternet);
return 1;
}
if (dwStatusCode == HTTP_STATUS_OK)
{
CHAR szBuffer[1024];
DWORD dwRead = 0;
while (InternetReadFile(hRequest, szBuffer, sizeof(szBuffer), &dwRead) && dwRead != 0)
{
// 处理响应数据
}
}
InternetCloseHandle(hRequest);
InternetCloseHandle(hConnect);
InternetCloseHandle(hInternet);
return 0;
}
```
该示例代码使用了WinINet库中的四个函数:InternetOpen、InternetConnect、HttpOpenRequest和HttpSendRequest,分别用于打开Internet会话、连接服务器、打开HTTP请求和发送HTTP请求。其中,HttpQueryInfo函数用于查询HTTP响应的状态码。在处理响应数据时,可以使用InternetReadFile函数从服务器读取数据。
阅读全文