1 /*****************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
9 * An example source code that issues a HTTP POST and we provide the actual
10 * data through a read callback.
15 #include <curl/curl.h>
17 const char data[]="this is what we post to the silly web server";
24 static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *userp)
26 struct WriteThis *pooh = (struct WriteThis *)userp;
32 *(char *)ptr = pooh->readptr[0]; /* copy one single byte */
33 pooh->readptr++; /* advance pointer */
34 pooh->sizeleft--; /* less data left */
35 return 1; /* we return 1 byte at a time! */
38 return 0; /* no more data left to deliver */
46 struct WriteThis pooh;
49 pooh.sizeleft = strlen(data);
51 curl = curl_easy_init();
53 /* First set the URL that is about to receive our POST. */
54 curl_easy_setopt(curl, CURLOPT_URL, "http://example.com/index.cgi");
56 /* Now specify we want to POST data */
57 curl_easy_setopt(curl, CURLOPT_POST, 1L);
59 /* we want to use our own read function */
60 curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);
62 /* pointer to pass to our read function */
63 curl_easy_setopt(curl, CURLOPT_READDATA, &pooh);
65 /* get verbose debug output please */
66 curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
69 If you use POST to a HTTP 1.1 server, you can send data without knowing
70 the size before starting the POST if you use chunked encoding. You
71 enable this by adding a header like "Transfer-Encoding: chunked" with
72 CURLOPT_HTTPHEADER. With HTTP 1.0 or without chunked transfer, you must
73 specify the size in the request.
77 struct curl_slist *chunk = NULL;
79 chunk = curl_slist_append(chunk, "Transfer-Encoding: chunked");
80 res = curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
81 /* use curl_slist_free_all() after the *perform() call to free this
85 /* Set the expected POST size. If you want to POST large amounts of data,
86 consider CURLOPT_POSTFIELDSIZE_LARGE */
87 curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (curl_off_t)pooh.sizeleft);
92 Using POST with HTTP 1.1 implies the use of a "Expect: 100-continue"
93 header. You can disable this header with CURLOPT_HTTPHEADER as usual.
94 NOTE: if you want chunked transfer too, you need to combine these two
95 since you can only set one list of headers with CURLOPT_HTTPHEADER. */
97 /* A less good option would be to enforce HTTP 1.0, but that might also
98 have other implications. */
100 struct curl_slist *chunk = NULL;
102 chunk = curl_slist_append(chunk, "Expect:");
103 res = curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
104 /* use curl_slist_free_all() after the *perform() call to free this
109 /* Perform the request, res will get the return code */
110 res = curl_easy_perform(curl);
113 curl_easy_cleanup(curl);