libcurl以get方式请求服务器端文件
Posted phoenix tree
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了libcurl以get方式请求服务器端文件相关的知识,希望对你有一定的参考价值。
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方式请求服务器端文件的主要内容,如果未能解决你的问题,请参考以下文章
转asp.net(c#)使用HttpWebRequest附加携带请求参数以post方式模拟上传大文件(以图片为例)到Web服务器端