如何在没有 libcurl 的情况下在 C 中发出 HTTP 获取请求? [英] How to make an HTTP get request in C without libcurl?

查看:23
本文介绍了如何在没有 libcurl 的情况下在 C 中发出 HTTP 获取请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个 C 程序来生成一个获取请求而不使用任何外部库.这是否可能仅使用 C 库,使用套接字?我正在考虑制作一个http数据包(使用正确的格式)并将其发送到服务器.这是唯一可能的方法还是有更好的方法?

I want to write a C program to generate a Get Request without using any external libraries. Is this possible using only C libraries, using sockets ? I'm thinking of crafting a http packet(using proper formatting) and sending it to the server. Is this the only possible way or is there a better way ?

推荐答案

使用 BSD 套接字,或者,如果你有一些限制,假设你有一些 RTOS,一些更简单的 TCP 堆栈,比如 lwIP,你可以形成 GET/POST请求.

Using BSD sockets or, if you're somewhat limited, say you have some RTOS, some simpler TCP stack, like lwIP, you can form the GET/POST request.

有许多开源实现.以happyhttp"为例( http://scumways.com/happyhttp/happyhttp.html ).我知道,它是 C++,而不是 C,但唯一依赖于 C++"的是字符串/数组管理,因此很容易移植到纯 C.

There are a number of open-source implementations. See the "happyhttp" as a sample ( http://scumways.com/happyhttp/happyhttp.html ). I know, it is C++, not C, but the only thing that is "C++-dependant" there is a string/array management, so it is easily ported to pure C.

请注意,没有数据包",因为 HTTP 通常通过 TCP 连接传输,所以从技术上讲,只有 RFC 格式的符号流.由于 http 请求通常以连接-发送-断开的方式完成,因此实际上可以将其称为数据包".

Beware, there are no "packets", since HTTP is usually transfered over the TCP connection, so technically there is only a stream of symbols in RFC format. Since http requests are usually done in a connect-send-disconnect manner, one might actually call this a "packet".

基本上,一旦你有一个打开的套接字(sockfd)所有"你需要做的就是

Basically, once you have an open socket (sockfd) "all" you have to do is something like

char sendline[MAXLINE + 1], recvline[MAXLINE + 1];
char* ptr;

size_t n;

/// Form request
snprintf(sendline, MAXSUB, 
     "GET %s HTTP/1.0
"  // POST or GET, both tested and works. Both HTTP 1.0 HTTP 1.1 works, but sometimes 
     "Host: %s
"     // but sometimes HTTP 1.0 works better in localhost type
     "Content-type: application/x-www-form-urlencoded
"
     "Content-length: %d

"
     "%s
", page, host, (unsigned int)strlen(poststr), poststr);

/// Write the request
if (write(sockfd, sendline, strlen(sendline))>= 0) 
{
    /// Read the response
    while ((n = read(sockfd, recvline, MAXLINE)) > 0) 
    {
        recvline[n] = '';

        if(fputs(recvline, stdout) == EOF)
        {
            printf("fputs() error
");
        }

        /// Remove the trailing chars
        ptr = strstr(recvline, "

");

        // check len for OutResponse here ?
        snprintf(OutResponse, MAXRESPONSE,"%s", ptr);
    }          
}

这篇关于如何在没有 libcurl 的情况下在 C 中发出 HTTP 获取请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆