作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想编写一个 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/59043637/
我是一名优秀的程序员,十分优秀!