libghttp的异步方式

libghttp是一个纯C的http lib,还挺好用的
以下代码是采用异步方式下载文件,并且获取下载进度的代码

 

int download_http_file(char* url , char* save_file_path , long file_length , float* download_percentage)
{
    ghttp_request*		request = NULL;
    ghttp_status		status;
	ghttp_current_status download_progress;
    char*				buf = 0;
    int					bytes_read=0 , download_total_len = 0;
	FILE*				fp;
 
#ifdef _WIN32
	WORD wVersionRequested;
	WSADATA  wsaData;

	wVersionRequested =MAKEWORD( 1, 1 );
	WSAStartup( wVersionRequested, (LPWSADATA)&wsaData );
#endif

	fp = fopen( save_file_path , "wb+");

    request = ghttp_request_new();
    if(ghttp_set_uri(request, url) == -1) {
        return -1;
	}
    if(ghttp_set_type(request, ghttp_type_get) == -1) {
        return -1;
	}
	
	ghttp_set_sync(request, ghttp_async);
	ghttp_prepare(request);
	
	do{  
		status = ghttp_process(request);  
		if(status == ghttp_error)  {
			printf("download file failed\n");
			fclose(fp);
			ghttp_close(request);
			ghttp_request_destroy(request);
			return -1;  
		}
		// A solution
		download_progress = ghttp_get_status(request);
		if( download_percentage != 0 && file_length > 0 ) {
			*download_percentage = (float)(download_progress.bytes_read * 100.0 / file_length);
		}
	} while( status == ghttp_not_done );
	
	bytes_read = ghttp_get_body_len(request); 
	buf = ghttp_get_body(request);

	fwrite( buf ,bytes_read , 1 , fp);
	fclose(fp);

	*download_percentage = (float)(bytes_read * 100.0 / file_length);

	ghttp_close(request);
	ghttp_request_destroy(request);

    return 1;
}


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值