- 论坛徽章:
- 0
|
回复 #1 mq110 的帖子
补充一个抽取HTTP Header的例子,LZ别见怪哈:
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <curl/curl.h>
5 #include <curl/types.h>
6 #include <curl/easy.h>
7
8
9 size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream)
10 {
11 printf("%s--------------------------------------------------------\n", ptr);
12 char* ptr1 = (char*)ptr;
13 if (ptr1[0] == '\r' || ptr1[1] == '\n')
14 return 0;
15
16 return nmemb;
17 }
18
19
20 int main(int argc, char *argv[])
21 {
22 CURL *curl;
23 curl_global_init(CURL_GLOBAL_ALL);
24 curl=curl_easy_init();
25 curl_easy_setopt(curl, CURLOPT_URL, argv[1]);
26
27 curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, write_data);
28 curl_easy_perform(curl);
29 curl_easy_cleanup(curl);
30
31 exit(0);
32 } |
说明:在 cURL 网站的 curl_easy_setopt.3 -- man page 中可以看到如下字段:
CURLOPT_HEADERFUNCTION
Function pointer that should match the following prototype: size_t function( void *ptr, size_t size, size_t nmemb, void *stream);. 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 should be easy enough using this. The size of the data pointed to by ptr is size multiplied with nmemb. Do not assume that the header line is zero terminated! The pointer named stream is the one you set with the CURLOPT_WRITEHEADER option. The callback function must return the number of bytes actually taken care of , or return -1 to signal error to the library (it will cause it to abort the transfer with a CURLE_WRITE_ERROR return code).
- 其中红色字段表明,即使使用了 CURLOPT_HEADERFUNCTION 标志,也不代表传给回调函数的仅仅是 Http Header部分的缓冲区,而是带 Http Header 的整个 response 报文缓冲区,所以在会调用函数中用 \r\n 来判断 Http Header 的结束。
- 其中蓝色字段表明,回调函数应该返回实际传给回到函数的缓冲区总字节数 size * memb,否则回调函数第一次被调用后,就会失败。
[ 本帖最后由 frank_seng 于 2009-6-11 21:38 编辑 ] |
|