/*
* curlutil.h
*
* curl工具库,用来处理下载图片及其它资源
*
* Created on: 2012-10-22
* Author: joycube2
*/
#ifndef CURLUTIL_H_
#define CURLUTIL_H_
#include “curl.h”
#include “all_include.h”
#include “predef.h”
/*
* 内存对象,用来在每次读取到chunk后,暂时保存读到的数据
* 用来封装好,提供给外部调用
*
* samples:
*
* DownloadResources downloadResources;
* initDownloadResource(&downloadResources,url);
* download_image(&downloadResources);
* …
* freeDownloadResource(&downloadResources);
*/
struct DownloadResources {
char* url;
char* memoeryBuff;
size_t size;
};
/*
* 初始化downloadResource对象一些相差的初始化信息
*/
void initDownloadResource(DownloadResources* downloadResources, char* url) {
downloadResources->url = url;
downloadResources->memoeryBuff = NULL;
downloadResources->size = 0;
}
/*
* 释放分配的内存空间
*/
void freeDownloadResource(DownloadResources* downloadResources) {
if (downloadResources->memoeryBuff) {
free(downloadResources->memoeryBuff);
}
}
size_t write_data(char *responseContent, size_t size, size_t nmemb,
void *userdata) {
logDebug(“curl response: size:%d nmemb:%d”, size, nmemb);
size_t realSize = size * nmemb;
struct DownloadResources* mem = (struct DownloadResources*) userdata;
if (mem->size == 0) {
mem->memoeryBuff = (char*) malloc(realSize);
memcpy(mem->memoeryBuff, responseContent, realSize);
} else {
mem->memoeryBuff = (char*) realloc(mem->memoeryBuff,
mem->size + realSize);
memcpy(mem->memoeryBuff + mem->size, responseContent, realSize);
}
mem->size += realSize;
return realSize;
}
/*
* 试试能不能直接给指针
*/
void download_image(DownloadResources* downloadResources) {
logInfo(“download %s”,downloadResources->url);
CURL * curl;
CURLcode res;
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, downloadResources->url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, downloadResources);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
if (res != CURLE_OK) {
logError(“failed:%s”, curl_easy_strerror(res));
}
} else {
logError(“failed:%s”, curl_easy_strerror(res));
}
}
#endif /* CURLUTIL_H_ */
0 条评论。