1. 程式人生 > >libcurl以get方式請求服務器端文件

libcurl以get方式請求服務器端文件

cti ati set printf libcurl lba map lean creat

static size_t callbackfunction(void *ptr, size_t size, size_t nmemb, void* userdata)
{
FILE* stream = (FILE*)userdata;
if (!stream) {
printf("!!! No stream\n");
return 0;
}

size_t written = fwrite((FILE*)ptr, size, nmemb, stream);
return written;

}

unsigned char* HttpsRequest::requestOnlineImage(const char* url, int& resultLen)
{
FILE* fp = fopen("D:\\out.png", "wb");
if (!fp) {

printf("!!! Failed to create file on the disk\n");
return false;
}

unsigned char* result = NULL;
CURL* mCurl = curl_easy_init();
if (!mCurl) {
return NULL;

}
//struct curl_slist* mHeaders = NULL;

//mHeaders = curl_slist_append(mHeaders, "Cache-Control:max-age=0");
//mHeaders = curl_slist_append(mHeaders, "Connection:keep-alive");
//mHeaders = curl_slist_append(mHeaders, "*/*");
//mHeaders = curl_slist_append(mHeaders, "Host:cpi.cn-hangzhou.oss-pub.aliyun-inc.com");
// mHeaders = curl_slist_append(mHeaders, "User-Agent:com.yunos.map/pc");
//mHeaders = curl_slist_append(mHeaders, "Content-type:image/png");
//mHeaders = curl_slist_append(mHeaders, "Response-type:application/octet-stream");
//mHeaders = curl_slist_append(mHeaders, "Accept-Encoding:gzip, deflate");

struct MemoryStruct chunk;
chunk.memory = (unsigned char*)malloc(1);
chunk.size = 0;
curl_easy_setopt(mCurl, CURLOPT_URL, url);
//curl_easy_setopt(mCurl, CURLOPT_HTTPHEADER, mHeaders);
curl_easy_setopt(mCurl, CURLOPT_WRITEFUNCTION, callbackfunction);
curl_easy_setopt(mCurl, CURLOPT_WRITEDATA, fp);
CURLcode mRes = curl_easy_perform(mCurl);

if (mRes != CURLE_OK){
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(mRes));

}
else {
printf("%s\n", chunk.memory);
if (chunk.size > 0) {
result = (unsigned char*)malloc(chunk.size);
memcpy(result, chunk.memory, chunk.size);
resultLen = chunk.size;
}
}
curl_slist_free_all(mHeaders);
free(chunk.memory);
curl_easy_cleanup(mCurl);
mCurl = NULL;
return result;

}

libcurl以get方式請求服務器端文件