Overview
While libcurl is extremely flexible in what it allows you to do, that flexibility comes at complexity price. The convenience wrappers defined here aim to take away some of that complexity for run-of-the-mill requests.
- A Basic Example
If all you need to do is receive a document into a buffer...
char *url = "https://someurl";
size_t returned_length;
char *returned_data = NULL;
long rc = ast_curler_simple(url, &returned_length, &returned_data, NULL);
ast_log(LOG_ERROR, "rc: %ld size: %zu doc: %.*s \n",
rc, returned_length,
(int)returned_length, returned_data);
ast_free(returned_data);
If you need the headers as well...
char *url = "https://someurl";
size_t returned_length;
char *returned_data = NULL;
long rc = ast_curler_simple(url, &returned_length, &returned_data,
&headers);
ast_log(LOG_ERROR, "rc: %ld size: %zu doc: %.*s \n",
rc, returned_length,
(int)returned_length, returned_data);
ast_free(returned_data);
- A More Complex Example
If you need more control, you can specify callbacks to capture the response headers, do something other than write the data to a memory buffer, or do some special socket manipulation like check that the server's IP address matched an acl.
Let's write the data to a file, capture the headers, and make sure the server's IP address is whitelisted.
The default callbacks can do that so all we need to do is supply the data.
char *url = "http://something";
struct ast_curl_write_data data = {
.output = fopen("myfile.txt", "w");
.debug_info = url,
};
struct ast_curl_header_data hdata = {
.debug_info = url,
};
struct ast_curl_open_socket_data osdata = {
.acl = my_acl_list,
.debug_info = url,
};
struct ast_curl_optional_data opdata = {
.open_socket_cb = ast_curl_open_socket_cb,
.open_socket_data = &osdata,
};
long rc = ast_curler(url, 0, ast_curl_write_default_cb, &data,
ast_curl_header_default_cb, &hdata, &opdata);
fclose(data.output);
If you need even more control, you can supply your own callbacks as well. This is a silly example of providing your own write callback. It's basically what ast_curler_write_to_file() does.
static size_t my_write_cb(char *data, size_t size,
size_t nmemb, void *client_data)
{
FILE *fp = (FILE *)client_data;
return fwrite(data, size, nmemb, fp);
}
static long myfunc(char *url, char *file)
{
FILE *fp = fopen(file, "w");
long rc = ast_curler(url, 0, my_write_cb, fp, NULL, NULL, NULL);
fclose(fp);
return rc;
}