bb440509a7c04cac0315ccc29562de80413aa791
[fedora-mingw.git] / curl / test1.c
1 /* Test using curl to fetch pages, look at headers, cookies. */
2
3 #include <stdio.h>
4 #include <stdlib.h>
5
6 #include <curl/curl.h>
7
8 static const char *url = "https://fedoraproject.org/wiki/MinGW";
9
10 static int bytes_received = 0;
11
12 static size_t
13 write_fn (void *ptr, size_t size, size_t nmemb, void *stream)
14 {
15   int bytes = size * nmemb;
16   bytes_received += bytes;
17   return bytes;
18 }
19
20 static size_t
21 header_fn (void *ptr, size_t size, size_t nmemb, void *stream)
22 {
23   int bytes = size * nmemb;
24   int i;
25
26   /* Note that we are called once for each header, but the
27    * header data is not NUL-terminated.  However we expect each
28    * header is terminated by \r\n.  Hence:
29    */
30   for (i = 0; i < bytes; ++i)
31     putchar (((char *)ptr)[i]);
32
33   return bytes;
34 }
35
36 int
37 main ()
38 {
39   CURLcode r;
40   CURL *curl;
41   long code;
42
43   r = curl_global_init (CURL_GLOBAL_ALL);
44   if (r != 0) {
45     fprintf (stderr, "curl_global_init failed with code %d\n", r);
46     exit (1);
47   }
48
49   curl = curl_easy_init ();
50   if (curl == NULL) {
51     fprintf (stderr, "curl_easy_init failed\n");
52     exit (1);
53   }
54
55   r = curl_easy_setopt (curl, CURLOPT_URL, url);
56   if (r != CURLE_OK) {
57     fprintf (stderr, "curl_easy_setopt CURLOPT_URL failed with code %d\n", r);
58     exit (1);
59   }
60
61   r = curl_easy_setopt (curl, CURLOPT_WRITEFUNCTION, write_fn);
62   if (r != CURLE_OK) {
63     fprintf (stderr, "curl_easy_setopt CURLOPT_WRITEFUNCTION failed with code %d\n", r);
64     exit (1);
65   }
66
67   r = curl_easy_setopt (curl, CURLOPT_HEADERFUNCTION, header_fn);
68   if (r != CURLE_OK) {
69     fprintf (stderr, "curl_easy_setopt CURLOPT_HEADERFUNCTION failed with code %d\n", r);
70     exit (1);
71   }
72
73   /* This enables cookie handling in libcurl: */
74   r = curl_easy_setopt (curl, CURLOPT_COOKIEFILE, "");
75   if (r != CURLE_OK) {
76     fprintf (stderr, "curl_easy_setopt CURLOPT_COOKIEFILE failed with code %d\n", r);
77     exit (1);
78   }
79
80   /* Fetch the page. */
81   printf ("fetching %s ...\n", url);
82   r = curl_easy_perform (curl);
83   if (r != CURLE_OK) {
84     fprintf (stderr, "curl_easy_perform failed with code %d\n", r);
85     exit (1);
86   }
87   printf ("... ok, bytes received in body was %d\n", bytes_received);
88
89   r = curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, &code);
90   if (r != CURLE_OK) {
91     fprintf (stderr, "curl_easy_getinfo CURLINFO_RESPONSE_CODE failed with code %d\n", r);
92     exit (1);
93   }
94   printf ("HTTP response code: %d\n", (int) code);
95
96   curl_easy_cleanup (curl);
97   curl_global_cleanup ();
98   exit (0);
99 }