c-program:curl写作正文

时间:2018-03-30 22:34:34

标签: c libcurl

在我的c程序中,我尝试使用libcurl从本地网络服务器获取数据。 这是我的代码:

int main() {
    CURL *curl;
    CURLcode res;
    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();
    curl_easy_setopt( curl, CURLOPT_URL, "localhost:3000/employees/2" );
    curl_easy_setopt( curl, CURLOPT_WRITEFUNCTION, write_data );
    res = curl_easy_perform(curl);
    ...
}

回调函数write_data如下所示:

size_t write_data(void *buffer, size_t size, size_t nmemb, void *userp) { 
    return size;
}

当libcurl调用我的回调函数" buffer"包含预期的数据。 但是我遇到了这个错误:

Failed writing body ( 1!= 105)
Closing connection
curl_easy_perform() failed: res = 23
error = failed writing received data to disk/application

当我没有设置回调函数时,它会起作用。

卷曲教程说: libcurl提供了自己的默认内部回调,如果您没有使用CURLOPT_WRITEFUNCTION设置回调,它将处理数据。然后它会将收到的数据输出到stdout。

但是,由于我正在设置回调,我不明白为什么curl显然会尝试写我的数据呢?

我做错了什么?

1 个答案:

答案 0 :(得分:1)

write_data()函数必须返回大小为* nmemb的字节。显然它被传递的大小为1,nmemb设置为105.你返回1,所以curl说它从1开始就没有足够的字节!= 105.