xref: /curl/docs/examples/headerapi.c (revision f540e43b)
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at https://curl.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  * SPDX-License-Identifier: curl
22  *
23  ***************************************************************************/
24 /* <DESC>
25  * Extract headers post transfer with the header API
26  * </DESC>
27  */
28 #include <stdio.h>
29 #include <curl/curl.h>
30 
write_cb(char * data,size_t n,size_t l,void * userp)31 static size_t write_cb(char *data, size_t n, size_t l, void *userp)
32 {
33   /* take care of the data here, ignored in this example */
34   (void)data;
35   (void)userp;
36   return n*l;
37 }
38 
main(void)39 int main(void)
40 {
41   CURL *curl;
42 
43   curl = curl_easy_init();
44   if(curl) {
45     CURLcode res;
46     struct curl_header *header;
47     curl_easy_setopt(curl, CURLOPT_URL, "https://example.com");
48     /* example.com is redirected, so we tell libcurl to follow redirection */
49     curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
50 
51     /* this example just ignores the content */
52     curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_cb);
53 
54     /* Perform the request, res gets the return code */
55     res = curl_easy_perform(curl);
56     /* Check for errors */
57     if(res != CURLE_OK)
58       fprintf(stderr, "curl_easy_perform() failed: %s\n",
59               curl_easy_strerror(res));
60 
61     if(CURLHE_OK == curl_easy_header(curl, "Content-Type", 0, CURLH_HEADER,
62                                      -1, &header))
63       printf("Got content-type: %s\n", header->value);
64 
65     printf("All server headers:\n");
66     {
67       struct curl_header *h;
68       struct curl_header *prev = NULL;
69       do {
70         h = curl_easy_nextheader(curl, CURLH_HEADER, -1, prev);
71         if(h)
72           printf(" %s: %s (%u)\n", h->name, h->value, (int)h->amount);
73         prev = h;
74       } while(h);
75 
76     }
77     /* always cleanup */
78     curl_easy_cleanup(curl);
79   }
80   return 0;
81 }
82