c++代码不使用curl进行post提交
时间: 2023-06-24 19:07:13 浏览: 101
C++实现POST请求
可以使用C++的网络编程库,如Socket或Boost.Asio来发送HTTP POST请求。以下是一个使用Socket的示例代码:
```c++
#include <iostream>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
int main() {
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
std::cerr << "WSAStartup failed: " << iResult << std::endl;
return 1;
}
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == INVALID_SOCKET) {
std::cerr << "socket failed: " << WSAGetLastError() << std::endl;
WSACleanup();
return 1;
}
sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
serverAddr.sin_port = htons(8080);
iResult = connect(s, (SOCKADDR*)&serverAddr, sizeof(serverAddr));
if (iResult == SOCKET_ERROR) {
std::cerr << "connect failed: " << WSAGetLastError() << std::endl;
closesocket(s);
WSACleanup();
return 1;
}
std::string postData = "param1=value1¶m2=value2";
std::string request = "POST /api HTTP/1.1\r\n"
"Host: 127.0.0.1:8080\r\n"
"Content-Type: application/x-www-form-urlencoded\r\n"
"Content-Length: " + std::to_string(postData.length()) + "\r\n"
"\r\n"
+ postData;
iResult = send(s, request.c_str(), request.length(), 0);
if (iResult == SOCKET_ERROR) {
std::cerr << "send failed: " << WSAGetLastError() << std::endl;
closesocket(s);
WSACleanup();
return 1;
}
char response[1024];
iResult = recv(s, response, sizeof(response), 0);
if (iResult > 0) {
std::cout << "Response: " << std::string(response, iResult) << std::endl;
}
else if (iResult == 0) {
std::cerr << "Connection closed" << std::endl;
}
else {
std::cerr << "recv failed: " << WSAGetLastError() << std::endl;
}
closesocket(s);
WSACleanup();
return 0;
}
```
此代码使用Socket连接到本地主机的8080端口,发送一个带有两个参数的POST请求。您需要将127.0.0.1和8080替换为您实际要连接的主机和端口,以及postData中包含的实际数据。
阅读全文