前些时间,由于找不到一个比较好使用的http库,自己封装了一个,不过时间紧迫,也没有完整分析HTTP协议,因此心里总不塌实地使用它,一次偶然的机会,让我在网上找到一个好用的http库 -- libghttp,目前的版本因该是libghttp-1.0.9. 这个库十分的方便使用,它能够轻松地实现同步和异步的Http请求。
简单使用实例:
#include <ghttp.h>
int main(int argc, char *argv[])
{
char *uri = "http://www.hao123.com";
ghttp_request *request = NULL;
ghttp_status status;
char *buf;
int bytes_read;
request = ghttp_request_new();
if(ghttp_set_uri(request, uri) == -1)
exit(-1);
if(ghttp_set_type(request, ghttp_type_get) == -1)
exit(-1);
ghttp_prepare(request);
status = ghttp_process(request);
if(status == ghttp_error)
exit(-1);
/* OK, done */
printf("Status code -> %d\n", ghttp_status_code(request));
buf = ghttp_get_body(loader->request);
bytes_read = ghttp_get_body_len(loader->request);
return 0;
}
异步请求实例:#include <ghttp.h>
int main(int argc, char *argv[])
{
char *uri = "http://www.hao123.com";
ghttp_request *request = NULL;
ghttp_status status;
char *buf;
int bytes_read;
request = ghttp_request_new();
if(ghttp_set_uri(request, uri) == -1)
exit(-1);
if(ghttp_set_type(request, ghttp_type_get) == -1)
exit(-1);
/* NOTE: Set async request */
ghttp_set_sync(request, ghttp_async);
ghttp_prepare(request);
while(1) {
status = ghttp_process(request);
if(status == ghttp_error)
break;
/* NOTE: buf may NULL, notice it */
buf = ghttp_get_body(loader->request);
bytes_read = ghttp_get_body_len(loader->request);
if(status == ghttp_done) {
/* NOTE: Ok, done */
break;
}
}
return 0;
}
http://hi.baidu.com/xiaoxiaolq/blog/item/d5c2c21ba3c262dfac6e7579.html
联系客服