libcurl使用HTTP的get请求来下载文件

首先设置好下载链接

int ret = curl_easy_setopt(easy_handle, CURLOPT_URL, "http://speedtest.wdc01.softlayer.com/downloads/test10.zip");

然后设置CURLOPT_WRITEFUNCTION属性保存接受的数据

ret |= curl_easy_setopt(easy_handle, CURLOPT_WRITEFUNCTION, write_callback);
write_callback是用户自定义的回调函数,用来保存接受到的数据,其原型为
size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata);

此函数返回实际接受到的字节数,如果返回的字节数与发送的不一致会导致中断传输。其中ptr表示接受的数据,size表示单块数据的大小,nmemb表示有几块数据,size*nmemb表示数据的大小,userdata表示用户自定义的参数,通过设置CURLOPT_WRITEDATA属性来传递,可以将其设置为文件指针,这样就可以保存接受到的数据了,如果是写C++,此函数应声明为static函数

Your callback should return the number of bytes actually taken care of. If that amount differs from the amount passed to your callback function, it'll signal an error condition to the library. This will cause the transfer to get aborted and the libcurl function used will return CURLE_WRITE_ERROR.

FILE *fp;
fopen_s(&fp, "test10.zip", "ab+"); // windows下的,linux平台用fopen
ret |= curl_easy_setopt(easy_handle, CURLOPT_WRITEDATA, fp); // fp当作参数传递给write_callback函数


write_callback的实现

size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata)
{
	FILE *fp = static_cast<FILE *>(userdata);
	size_t length = fwrite(ptr, size, nmemb, fp);
	if (length != nmemb)
	{
		return length;
	}

	return size * nmemb;
}

整个工程的GitHub地址:https://github.com/zyumle/HttpClient



版权声明:本文为博主原创文章,未经博主允许不得转载。

你可能感兴趣的:(http,get,curl,libcurl)