大家都很熟悉HTTP协议的应用,因为每天都在网络上浏览着不少东西,也都知道是HTTP协议是相当简单的。每次用到FlashGet之类的下载软件下载网页,当用到那个“用FlashGet下载全部链接”时总觉得很神奇。
后来想想,其实要实现这些下载功能也并不难,只要按照HTTP协议发送request,然后对接收到的数据进行分析,如果页面上还有href之类的链接指向标志就可以进行深一层的下载了。HTTP协议目前用的最多的是1.1版本,要全面透彻地搞懂它就参考RFC2616文档吧。下面是我用C语言编程写的一个http下载程序,希望对大家有些启发。源代码如下:
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <errno.h>
- #include <unistd.h>
- #include <netinet/in.h>
- #include <limits.h>
- #include <netdb.h>
- #include <arpa/inet.h>
- #include <ctype.h>
- //////////////////////////////httpclient.c 开始///////////////////////////////////////////
- /********************************************
- 功能:搜索字符串右边起的第一个匹配字符
- ********************************************/
- char * Rstrchr(char * s, char x) {
- int i = strlen(s);
- if(!(*s)) return 0;
- while(s[i-1]) if(strchr(s + (i - 1), x)) return (s + (i - 1)); else i--;
- return 0;
- }
- /********************************************
- 功能:把字符串转换为全小写
- ********************************************/
- void ToLowerCase(char * s) {
- while(*s) *s=tolower(*s++);
- }

这篇博客展示了如何用C语言编程实现一个简单的HTTP协议客户端,该程序可以从指定URL下载网页内容。通过分析URL获取网站地址、端口和文件名,然后建立TCP连接,发送HTTP GET请求并接收响应,将内容保存到本地文件。
最低0.47元/天 解锁文章
996

被折叠的 条评论
为什么被折叠?



