实现一个简单的HTTP请求,可以使用socket库来进行,该库在C语言中内置,可以在不依赖任何第三方库的情况下使用。以下是一个简单的实现示例:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>

#define MAXLINE 1024

int main(int argc, char **argv) {
    int sockfd, port, n;
    char *ipaddr, *host, *path, *cookie, *postdata;
    char sendline[MAXLINE], recvline[MAXLINE], buf[MAXLINE];
    struct sockaddr_in servaddr;
    struct hostent *ht;

    if (argc != 3) {
        printf('usage: %s <url> <postdata>
', argv[0]);
        exit(-1);
    }

    /* 解析参数 */
    host = strtok(argv[1], '/');
    path = strtok(NULL, '/');
    postdata = argv[2];

    if ((ht = gethostbyname(host)) == NULL) {
        printf('gethostbyname error for host: %s
', host);
        exit(-1);
    }
    ipaddr = inet_ntoa(*((struct in_addr *) ht->h_addr_list[0]));
    port = 80;

    /* 建立socket连接 */
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        printf('socket error
');
        exit(-1);
    }

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(port);

    if (inet_pton(AF_INET, ipaddr, &servaddr.sin_addr) <= 0) {
        printf('inet_pton error for %s
', ipaddr);
        exit(-1);
    }

    if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) {
        printf('connect error
');
        exit(-1);
    }

    /* 发送HTTP请求 */
    sprintf(sendline, 'GET /%s HTTP/1.1
', path);
    sprintf(buf, 'Host: %s
', host);
    strcat(sendline, buf);
    strcat(sendline, 'Connection: keep-alive
');

    if (cookie) {
        sprintf(buf, 'Cookie: %s
', cookie);
        strcat(sendline, buf);
    }

    if (postdata) {
        sprintf(buf, 'Content-Length: %ld
', strlen(postdata));
        strcat(sendline, buf);
        strcat(sendline, 'Content-Type: application/x-www-form-urlencoded
');
    }

    strcat(sendline, '
');

    if (postdata) {
        strcat(sendline, postdata);
    }

    write(sockfd, sendline, strlen(sendline));

    /* 读取HTTP响应 */
    while ((n = read(sockfd, recvline, MAXLINE - 1)) > 0) {
        recvline[n] = 0;
        printf('%s', recvline);
    }

    if (n < 0) {
        printf('read error
');
        exit(-1);
    }

    close(sockfd);

    return 0;
}

该代码实现了一个简单的HTTP请求,支持GET和POST方法,可以设置Cookie,无需任何第三方库,跨平台。您可以通过传递URL和POST数据来使用它。

不过,需要注意的是,该代码只是一个简单的实现示例,不适用于生产环境。在实际应用中,您需要考虑更多的细节和安全问题。

C语言零依赖实现HTTP请求:GET、POST、Cookie支持,跨平台代码示例

原文地址: https://www.cveoy.top/t/topic/oyRw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录