【发布时间】:2016-09-27 18:12:30
【问题描述】:
我正在实现一个 C 程序,它需要从 Content-Length 标头中读取远程文件的大小(当在响应标头中发送 Content-Length 时)。
我查看了 libcurl 的文档,到目前为止我能想到的最好的方法是 CURLOPT_HEADERFUNCTION 设置的回调函数。我已经整理了一个回调的玩具实现,它应该将标题打印到STDOUT:
size_t hdf(char* b, size_t size, size_t nitems, void *userdata) {
printf("%s", b);
return 0;
}
虽然我希望能够打印 Content-Length 标头(或者至少打印所有标头),但我只能使用此函数来打印响应代码:
$ ./curltest "some_url_which_sends_back_Content_Length"
HTTP/1.1 200 OK
如果我在main 中注释掉将回调设置为上面定义的hdf 函数的行,则默认行为是将所有标题打印到STDOUT。
作为参考,这是我正在使用的 main 函数,基于 libcurl 邮件列表中的一个线程:
int main(int argc, char *argv[])
{
CURLcode ret;
CURL *hnd = curl_easy_init();
curl_easy_setopt(hnd, CURLOPT_URL, argv[1]);
curl_easy_setopt(hnd, CURLOPT_HEADER, 1);
curl_easy_setopt(hnd, CURLOPT_NOBODY, 1);
curl_easy_setopt(hnd, CURLOPT_HEADERFUNCTION, hdf);
ret = curl_easy_perform(hnd);
curl_easy_cleanup(hnd);
}
如何为 CURLOPT_HEADERFUNCTION 选项编写回调,它可以将特定标头加载到内存中或以其他方式对其进行操作——或者至少将所有标头加载到内存中?
【问题讨论】: