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;
}


 

你可能感兴趣的:(异步下载,libghttp)