请用C语言写一个post请求,不允许使用curl库
时间: 2024-04-09 07:28:12 浏览: 125
纯C语言实现https的post和get,不依赖任何库
3星 · 编辑精心推荐
好的,以下是一个使用C语言编写的基本的POST请求示例,不使用curl库:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#define BUFFER_SIZE 1024
void error(const char *msg) {
perror(msg);
exit(1);
}
int create_tcp_socket() {
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
error("Error creating socket");
}
return sock;
}
char *get_ip(const char *host) {
struct hostent *hent;
int iplen = 15; //XXX.XXX.XXX.XXX
char *ip = (char *) malloc(iplen + 1);
memset(ip, 0, iplen + 1);
if ((hent = gethostbyname(host)) == NULL) {
error("Error getting IP");
}
if (inet_ntop(AF_INET, (void *) hent->h_addr_list[0], ip, iplen) == NULL) {
error("Error converting hostname to IP address");
}
return ip;
}
char *build_post_request(const char *host, const char *path, const char *content_type, const char *body) {
char *request_format = "POST %s HTTP/1.1\r\n"
"Host: %s\r\n"
"Content-Type: %s\r\n"
"Content-Length: %ld\r\n"
"Connection: close\r\n"
"\r\n"
"%s";
int request_length = snprintf(NULL, 0, request_format, path, host, content_type, strlen(body), body);
char *request = (char *) malloc(request_length + 1);
sprintf(request, request_format, path, host, content_type, strlen(body), body);
return request;
}
void send_post_request(const char *host, const char *port, const char *path, const char *content_type, const char *body) {
int sock = create_tcp_socket();
char *ip = get_ip(host);
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(atoi(port));
if (inet_pton(AF_INET, ip, &(server_address.sin_addr)) <= 0) {
error("Error converting IP address");
}
if (connect(sock, (struct sockaddr *) &server_address, sizeof(server_address)) == -1) {
error("Error connecting to server");
}
char *request = build_post_request(host, path, content_type, body);
if (send(sock, request, strlen(request), 0) == -1) {
error("Error sending request");
}
char response[BUFFER_SIZE];
memset(response, 0, sizeof(response));
while (1) {
int bytes_received = recv(sock, response, BUFFER_SIZE - 1, 0);
if (bytes_received <= 0) {
break;
}
printf("%s", response);
memset(response, 0, sizeof(response));
}
free(request);
free(ip);
close(sock);
}
int main() {
const char *host = "example.com";
const char *port = "80";
const char *path = "/your/api/endpoint";
const char *content_type = "application/json";
const char *body = "{\"key\":\"value\"}";
send_post_request(host, port, path, content_type, body);
return 0;
}
```
请将`example.com`替换为目标主机的域名或IP地址,`/your/api/endpoint`替换为实际的API端点,`{\"key\":\"value\"}`替换为您要发送的请求体内容。
阅读全文