gpt4 book ai didi

c - 如何使用 CURLOPT_HEADERFUNCTION 读取单个响应头字段?

转载 作者:太空狗 更新时间:2023-10-29 14:57:10 25 4
gpt4 key购买 nike

我正在实现一个 C 程序,它需要从 Content-Length header 中读取远程文件的大小(当 Content-Length 在响应 header 中发送时) .

我查看了 libcurl 的文档,到目前为止我能想到的最好的方法是 CURLOPT_HEADERFUNCTION 设置的回调函数。我整理了一个回调的玩具实现,它应该将 header 打印到 STDOUT:

size_t hdf(char* b, size_t size, size_t nitems, void *userdata) {
printf("%s", b);
return 0;
}

虽然我希望能够打印 Content-Length header (或者至少打印所有 header ),但我只能使用此函数来打印响应代码:

$ ./curltest "some_url_which_sends_back_Content_Length"
HTTP/1.1 200 OK

如果我在 main 中注释掉将回调设置为上面定义的 hdf 函数的行,则默认行为是将所有 header 打印到 标准输出

作为引用,这是我正在使用的 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 选项编写回调,它可以将特定 header 加载到内存中或以其他方式对其进行操作——或者至少将所有 header 加载到内存中?

最佳答案

I can only get this function to print the response code:

答案在 CURLOPT_HEADERFUNCTION 中文档:

This function gets called by libcurl as soon as it has received header data. The header callback will be called once for each header and only complete header lines are passed on to the callback. Parsing headers is very easy using this. The size of the data pointed to by buffer is size multiplied with nmemb. Do not assume that the header line is zero terminated! The pointer named userdata is the one you set with the CURLOPT_HEADERDATA option. This callback function must return the number of bytes actually taken care of. If that amount differs from the amount passed in to your function, it'll signal an error to the library. This will cause the transfer to get aborted and the libcurl function in progress will return CURLE_WRITE_ERROR.

你的 printf()调用假定为空终止,并且您的回调返回的字节数少于提供的字节数,因此您将在收到第一个响应行后中止响应。

试试这个。

size_t hdf(char* b, size_t size, size_t nitems, void *userdata) {
size_t numbytes = size * nitems;
printf("%.*s\n", numbytes, b);
return numbytes;
}

How can I write a callback for the CURLOPT_HEADERFUNCTION option which can load a specific header into memory or otherwise manipulate it -- or, at least, load all headers into memory?

修复错误后,您应该能够看到所有 header 。然后您可以解析 b寻找 Content-Length header ,并在找到时将其数据保存到您传递给 userdata 的缓冲区中通过CURLOPT_HEADERDATA .

话虽如此,现在有一种更简单的方法来检索 Content-Length 值。执行 HEADcurl_easy_perform() 请求( CURLOPT_NOBODY ),如果成功则使用 curl_easy_getinfo()检索 CURLINFO_CONTENT_LENGTH_DOWNLOAD 值:

CURLINFO_CONTENT_LENGTH_DOWNLOAD
Content length from the Content-Length header.

关于c - 如何使用 CURLOPT_HEADERFUNCTION 读取单个响应头字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37516773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com