写一个c/c++ 使用wininet库向www.baidu.com发送HTTP POST/GET请求的代码
时间: 2024-10-04 15:02:52 浏览: 42
在C/C++中使用WinINET库(Windows Internet Network Library)发送HTTP GET或POST请求通常涉及到`INTERNETCOMMUNICATOR`结构、`INTERNETCONNECT`函数以及`INTERNETREQUEST`等API。这里给出一个简单的示例,展示如何发送GET和POST请求到www.baidu.com:
```cpp
#include <windows.h>
#include <wininet.h>
// 发送GET请求
void send_GET_request(LPCSTR url) {
HINTERNET hSession = NULL;
HINTERNET hConnect = NULL;
HINTERNET hRequest = NULL;
// 初始化WinINET
hSession = InternetOpen(NULL, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
if (hSession) {
// 连接到服务器
hConnect = InternetConnect(hSession, url, INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, 0, 0, 0);
if (hConnect) {
// 创建请求
hRequest = HttpOpenRequest(hConnect, _T("GET"), url, NULL, NULL, _T("HTTP/1.1"), INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE, NULL);
if (hRequest) {
// 发起请求并接收响应
DWORD dwResponse = 0;
char szBuffer[4096];
if (HttpSendRequest(hRequest, NULL, 0, NULL, 0, szBuffer, sizeof(szBuffer), &dwResponse)) {
printf("GET Response:\n%s\n", szBuffer);
}
InternetCloseHandle(hRequest);
}
InternetCloseHandle(hConnect);
}
InternetCloseHandle(hSession);
} else {
printf("Error initializing WinINET: %d\n", GetLastError());
}
}
// 发送POST请求,这里仅做示例,实际应用需要处理POST数据
void send_POST_request(LPCSTR url, LPCSTR postData) {
HINTERNET hSession, hConnect, hRequest;
hSession = InternetOpen(NULL, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
hConnect = InternetConnect(hSession, url, INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, 0, 0, 0);
if (hConnect) {
hRequest = HttpOpenRequest(hConnect, _T("POST"), url, NULL, NULL, _T("HTTP/1.1"), INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE, NULL);
if (hRequest) {
LPCTSTR lpPostData = postData;
DWORD dwContentLength = lstrlen(lpPostData);
DWORD dwIndex = 0;
const char* boundary = "--WebKitFormBoundary7MA4YWxkTrZu0gW"; // 示例中的边界值
// 添加请求头
HttpAddRequestHeader(hRequest, _T("Content-Type"), _T("multipart/form-data; boundary=") + boundary, -1);
// 发送POST数据
while (dwIndex < dwContentLength) {
HttpSendRequestChunk(hRequest, boundary, strlen(boundary), lpPostData + dwIndex, 1);
dwIndex += strlen(lpPostData) + 1;
}
// 结束POST数据
HttpSendRequestChunk(hRequest, "\r\n--\r\n", -1, NULL, 0);
// 接收响应
DWORD dwResponse = 0;
char szBuffer[4096];
if (HttpSendRequest(hRequest, NULL, 0, NULL, 0, szBuffer, sizeof(szBuffer), &dwResponse)) {
printf("POST Response:\n%s\n", szBuffer);
}
InternetCloseHandle(hRequest);
}
InternetCloseHandle(hConnect);
}
InternetCloseHandle(hSession);
}
int main() {
send_GET_request("http://www.baidu.com");
send_POST_request("http://www.baidu.com", "Your data here"); // 替换为实际的POST数据
return 0;
}
```
注意这只是一个基本示例,并未包含错误处理和完整的POST数据处理。在实际项目中,你需要处理更多的细节,比如添加用户认证信息、设置超时、解析响应内容等。
阅读全文