使用HTTP GET请求C时不libcurl的 [英] HTTP get Request using C WITHOUT libCurl
问题描述
我想写一个C程序来生成一个GET请求,而无需使用任何外部库。仅使用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\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) { cout << ("fputs erros"); }
/// Remove the trailing chars
ptr = strstr(recvline, "\r\n\r\n");
// check len for OutResponse here ?
snprintf(OutResponse, MAXRESPONSE,"%s", ptr);
}
}
这篇关于使用HTTP GET请求C时不libcurl的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!