我想编写一个 C 程序来生成一个 Get 请求,而不使用任何外部库。这可能仅使用 C 库,使用套接字吗?我正在考虑制作一个 http 数据包(使用正确的格式)并将其发送到服务器。这是唯一可能的方法还是有更好的方法?
最佳答案
使用 BSD 套接字,或者,如果您有一些限制,假设您有一些 RTOS,一些更简单的 TCP 堆栈,如 lwIP,您可以形成 GET/POST 请求。
有许多开源实现。请参阅“happyhttp”作为示例 (http://scumways.com/happyhttp/happyhttp.html)。我知道,它是 C++,而不是 C,但唯一“依赖于 C++”的是字符串/数组管理,因此很容易移植到纯 C。
请注意,没有“数据包”,因为 HTTP 通常通过 TCP 连接传输,因此从技术上讲,只有 RFC 格式的符号流。由于 http 请求通常以连接-发送-断开的方式完成,因此实际上可以将其称为“数据包”。
基本上,一旦你有一个打开的套接字(sockfd)“所有”你必须做的就是
char sendline[MAXLINE + 1], recvline[MAXLINE + 1];
char* ptr;
size_t n;
/// Form request
snprintf(sendline, MAXSUB,
"GET %s HTTP/1.0\r\n" // POST or GET, both tested and works. Both HTTP 1.0 HTTP 1.1 works, but sometimes
"Host: %s\r\n" // but sometimes HTTP 1.0 works better in localhost type
"Content-type: application/x-www-form-urlencoded\r\n"
"Content-length: %d\r\n\r\n"
"%s\r\n", 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] = '\0';
if(fputs(recvline, stdout) == EOF)
{
printf("fputs() error\n");
}
/// Remove the trailing chars
ptr = strstr(recvline, "\r\n\r\n");
// check len for OutResponse here ?
snprintf(OutResponse, MAXRESPONSE,"%s", ptr);
}
}
关于c - 如何在没有 libcurl 的情况下在 C 中发出 HTTP get 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11208299/