vc 实现post 发送json
时间: 2024-02-04 18:00:41 浏览: 43
在VC中实现POST发送JSON可以通过以下步骤实现:
1. 引入必要的头文件
在代码中引入以下头文件:
```c++
#include <iostream>
#include <string>
#include <winhttp.h>
```
2. 创建WinHTTP会话和连接
```c++
HINTERNET hSession = WinHttpOpen(L"WinHTTP Example/1.0",
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME,
WINHTTP_NO_PROXY_BYPASS, 0);
if (hSession == NULL) {
std::wcout << L"Failed to open WinHTTP session!" << std::endl;
return 1;
}
HINTERNET hConnect = WinHttpOpenRequest(hSession, L"POST", L"www.example.com",
NULL, WINHTTP_NO_REFERER,
WINHTTP_DEFAULT_ACCEPT_TYPES,
0);
if (hConnect == NULL) {
std::wcout << L"Failed to open WinHTTP connection!" << std::endl;
WinHttpCloseHandle(hSession);
return 1;
}
```
3. 设置请求头信息
```c++
std::wstring headerData = L"Content-Type: application/json; charset=utf-8\r\n";
BOOL setResult = WinHttpAddRequestHeaders(hConnect,
headerData.c_str(),
headerData.length(),
WINHTTP_ADDREQ_FLAG_ADD);
if (!setResult) {
std::wcout << L"Failed to set request headers!" << std::endl;
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return 1;
}
```
4. 发送JSON数据
```c++
std::wstring jsonData = L"{\"key\": \"value\"}";
setResult = WinHttpSendRequest(hConnect,
WINHTTP_NO_ADDITIONAL_HEADERS,
0,
(LPVOID)jsonData.c_str(),
jsonData.length(),
jsonData.length(),
0);
if (!setResult) {
std::wcout << L"Failed to send JSON data!" << std::endl;
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return 1;
}
```
5. 接收服务器响应
```c++
setResult = WinHttpReceiveResponse(hConnect, NULL);
if (!setResult) {
std::wcout << L"Failed to receive response!" << std::endl;
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return 1;
}
DWORD statusCode = 0;
DWORD statusCodeSize = sizeof(DWORD);
WinHttpQueryHeaders(hConnect, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, NULL, &statusCode, &statusCodeSize, NULL);
std::wcout << L"Response Status Code: " << statusCode << std::endl;
DWORD bytesRead = 0;
char buffer[4096];
std::wstring response;
while (WinHttpReadData(hConnect, buffer, sizeof(buffer), &bytesRead)) {
response.append(buffer, bytesRead);
if (bytesRead == 0) {
break;
}
}
std::wcout << L"Response Body: " << response << std::endl;
```
6. 清理资源
```c++
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
```
以上是使用VC实现POST发送JSON的基本步骤。根据实际需求,你可能需要进行适当的异常处理和参数配置。