C语言Socket实现Http的post请求

修改三个宏定义即可

#define HOST "192.168.1.133" //主机

#define PORT 80 //端口

#define POST_DATA "post_test=444&post_val=555" //内容

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

#define HOST "192.168.1.133"
#define PORT 80
#define POST_DATA "post_test=444&post_val=555"
#define POST_DATA_LENGTH strlen(POST_DATA)

int main() {
    int sockfd;
    struct sockaddr_in server_addr;
    struct hostent *server;

    // 创建套接字
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        perror("Error opening socket");
        exit(1);
    }

    // 获取服务器的IP地址
    server = gethostbyname(HOST);
    if (server == NULL) {
        fprintf(stderr,"Error: no such host\n");
        exit(1);
    }

    // 设置服务器地址结构
    bzero((char *) &server_addr, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    bcopy((char *)server->h_addr, (char *)&server_addr.sin_addr.s_addr, server->h_length);
    server_addr.sin_port = htons(PORT);

    // 连接到服务器
    if (connect(sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
        perror("Error connecting");
        exit(1);
    }

    // 构造HTTP请求
    char request[1024];
    sprintf(request, "POST /set HTTP/1.1\r\n"
                      "Host: %s\r\n"
                      "Content-Type: application/x-www-form-urlencoded\r\n"
                      "Content-Length: %zu\r\n"
                      "\r\n"
                      "%s", HOST, POST_DATA_LENGTH, POST_DATA);

    // 发送HTTP请求
    if (send(sockfd, request, strlen(request), 0) < 0) {
        perror("Error sending request");
        exit(1);
    }

    // 接收并显示服务器的响应
    char response[4096];
    int bytes_received = recv(sockfd, response, sizeof(response), 0);
    if (bytes_received < 0) {
        perror("Error receiving response");
        exit(1);
    }
    printf("Response from server:\n");
    fwrite(response, 1, bytes_received, stdout);

    // 关闭套接字
    close(sockfd);

    return 0;
}
相关推荐
大模型铲屎官8 分钟前
【Python-Day 14】玩转Python字典(上篇):从零开始学习创建、访问与操作
开发语言·人工智能·pytorch·python·深度学习·大模型·字典
yunvwugua__10 分钟前
Python训练营打卡 Day27
开发语言·python
Java致死1 小时前
设计模式Java
java·开发语言·设计模式
zh_xuan1 小时前
c++ 类的语法3
开发语言·c++
belldeep5 小时前
如何阅读、学习 Tcc (Tiny C Compiler) 源代码?如何解析 Tcc 源代码?
c语言·开发语言
LuckyTHP5 小时前
java 使用zxing生成条形码(可自定义文字位置、边框样式)
java·开发语言·python
Blossom.1188 小时前
使用Python实现简单的人工智能聊天机器人
开发语言·人工智能·python·低代码·数据挖掘·机器人·云计算
救救孩子把8 小时前
MCP本地高效与云端实时:stdio 与 HTTP+SSE 传输机制深度对比
网络·网络协议·http·sse·mcp·stdio
da-peng-song8 小时前
ArcGIS Desktop使用入门(二)常用工具条——数据框工具(旋转视图)
开发语言·javascript·arcgis
galaxy_strive8 小时前
qtc++ qdebug日志生成
开发语言·c++·qt