httplib post示例代码c++
时间: 2024-01-17 12:01:43 浏览: 146
C++模拟http post
5星 · 资源好评率100%
以下是一个httplib post示例代码的C++版本:
#include <iostream>
#include <sstream>
#include <string>
#include <ctime>
#include <cmath>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <vector>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
std::string createRequestBody(const std::string& data) {
std::ostringstream request;
request << "POST /upload HTTP/1.1\r\n";
request << "Host: example.com\r\n";
request << "Content-Type: application/x-www-form-urlencoded\r\n";
request << "Content-Length: " << data.length() << "\r\n\r\n";
request << data;
return request.str();
}
int main() {
int clientSocket = socket(AF_INET, SOCK_STREAM, 0);
if (clientSocket == -1) {
std::cout << "Failed to create socket." << std::endl;
return 1;
}
// 连接到服务器
sockaddr_in serverAddress{};
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(80);
serverAddress.sin_addr.s_addr = inet_addr("127.0.0.1");
if (connect(clientSocket, reinterpret_cast<struct sockaddr*>(&serverAddress), sizeof(serverAddress)) != 0) {
std::cout << "Failed to connect to the server." << std::endl;
return 1;
}
// 准备请求体
std::string requestData = "key1=value1&key2=value2";
// 创建请求
std::string requestBody = createRequestBody(requestData);
// 发送请求
if (send(clientSocket, requestBody.c_str(), requestBody.length(), 0) < 0) {
std::cout << "Failed to send the request." << std::endl;
}
// 接收响应
char serverResponse[4096];
memset(serverResponse, 0, sizeof(serverResponse));
if (recv(clientSocket, serverResponse, sizeof(serverResponse), 0) < 0) {
std::cout << "Failed to receive the server's response." << std::endl;
}
// 处理响应
std::cout << "Server Response: " << std::endl;
std::cout << serverResponse << std::endl;
// 关闭连接
close(clientSocket);
return 0;
}
以上代码实现了一个简单的httplib post请求的发送和接收响应过程。首先,它创建了一个套接字来进行与服务器的连接。然后,它构造了HTTP请求的请求体,并将其发送到服务器。之后,它接收来自服务器的响应,并将其打印到控制台上。最后,它关闭了套接字来终止与服务器的连接。在实际使用时,你需要根据实际情况修改服务器地址、端口以及请求体的内容。
阅读全文