1 /*****************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * $Id: post-callback.c,v 1.1.1.1 2008-09-23 16:32:05 hoffman Exp $
10 * An example source code that issues a HTTP POST and we provide the actual
11 * data through a read callback.
16 #include <curl/curl.h>
18 const char data
[]="this is what we post to the silly web server";
25 static size_t read_callback(void *ptr
, size_t size
, size_t nmemb
, void *userp
)
27 struct WriteThis
*pooh
= (struct WriteThis
*)userp
;
33 *(char *)ptr
= pooh
->readptr
[0]; /* copy one single byte */
34 pooh
->readptr
++; /* advance pointer */
35 pooh
->sizeleft
--; /* less data left */
36 return 1; /* we return 1 byte at a time! */
39 return 0; /* no more data left to deliver */
47 struct WriteThis pooh
;
50 pooh
.sizeleft
= strlen(data
);
52 curl
= curl_easy_init();
54 /* First set the URL that is about to receive our POST. */
55 curl_easy_setopt(curl
, CURLOPT_URL
,
56 "http://receivingsite.com.pooh/index.cgi");
57 /* Now specify we want to POST data */
58 curl_easy_setopt(curl
, CURLOPT_POST
, 1L);
60 /* we want to use our own read function */
61 curl_easy_setopt(curl
, CURLOPT_READFUNCTION
, read_callback
);
63 /* pointer to pass to our read function */
64 curl_easy_setopt(curl
, CURLOPT_READDATA
, &pooh
);
66 /* get verbose debug output please */
67 curl_easy_setopt(curl
, CURLOPT_VERBOSE
, 1L);
70 If you use POST to a HTTP 1.1 server, you can send data without knowing
71 the size before starting the POST if you use chunked encoding. You
72 enable this by adding a header like "Transfer-Encoding: chunked" with
73 CURLOPT_HTTPHEADER. With HTTP 1.0 or without chunked transfer, you must
74 specify the size in the request.
78 struct curl_slist
*chunk
= NULL
;
80 chunk
= curl_slist_append(chunk
, "Transfer-Encoding: chunked");
81 res
= curl_easy_setopt(curl
, CURLOPT_HTTPHEADER
, chunk
);
82 /* use curl_slist_free_all() after the *perform() call to free this
86 /* Set the expected POST size. If you want to POST large amounts of data,
87 consider CURLOPT_POSTFIELDSIZE_LARGE */
88 curl_easy_setopt(curl
, CURLOPT_POSTFIELDSIZE
, (curl_off_t
)pooh
.sizeleft
);
93 Using POST with HTTP 1.1 implies the use of a "Expect: 100-continue"
94 header. You can disable this header with CURLOPT_HTTPHEADER as usual.
95 NOTE: if you want chunked transfer too, you need to combine these two
96 since you can only set one list of headers with CURLOPT_HTTPHEADER. */
98 /* A less good option would be to enforce HTTP 1.0, but that might also
99 have other implications. */
101 struct curl_slist
*chunk
= NULL
;
103 chunk
= curl_slist_append(chunk
, "Expect:");
104 res
= curl_easy_setopt(curl
, CURLOPT_HTTPHEADER
, chunk
);
105 /* use curl_slist_free_all() after the *perform() call to free this
110 /* Perform the request, res will get the return code */
111 res
= curl_easy_perform(curl
);
114 curl_easy_cleanup(curl
);