curlCURLOPT_WRITEDATACURLOPT_WRITEFUNCTION
回调函数
最近⽤libcurl开源库做了⼀个项⽬,关于接收请求返回数据的回调函数,是我的⼀点想法。
1,curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, HttpPostWriteBack);
HttpPostWriteBack是回调函数指针,需要⾃⼰实现原型为:unsigned int HttpPostWriteBack(void *contents, size_t size, size_t nmemb, void *userp)
1)contents:返回数据指针;2)size:每⼀块⼤⼩;3)nmemb:块数;4)userp:出参数据,若想传出http返回数据,这是途径。
2,curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
chunk:回调函数的第四个参数,⽤来保存返回数据。
下⾯是⼀次完整请求的curl请求
struct MemoryStruct {
char *memory;
size_t size;
};//声明⼀个结构体
unsigned int HttpPostWriteBack(void *contents, size_t size, size_t nmemb, void *userp)
{//回调函数实现:⼀次请求可能多次调回调函数
size_t realsize = size * nmemb;//⼀次回调返回的数据量
struct MemoryStruct *mem = (struct MemoryStruct *)userp;
char *ptr = realloc(mem->memory, mem->size + realsize);
if (ptr == NULL) {
/* out of memory! */
LogOut("not enough memory (realloc returned NULL)\n");
return 0;
}
LogOut("chunk realloc success\n");
mem->memory = ptr;
memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
LogOut("callback mem->size :%d\n",mem->size);
return realsize;//必须返回真实的数据
}
write的返回值
int Serve_Http_Post(....)
{
struct MemoryStruct chunk;
< = malloc(1);
chunk.size = 0;
......
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, HttpPostWriteBack);
.......
curl_easy_perform(curl);
............已经有数据
if ()
{
);
< = NULL;        LogOut("chunk Free\n");    }
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。