#include <curl/curl.h>
#include <string.h>
static const char *const URL = "http://localhost:8000";
size_t recv_cb(char *ptr, size_t size, size_t nmemb, void *userdata) {
fprintf(stderr, "ptr = %p, size = %zu, nmemb = %zu, userdata = %p\n",
ptr, size, nmemb, userdata);
return fwrite(ptr, size, nmemb, (FILE *)userdata);
}
int main(void) {
curl_global_init(CURL_GLOBAL_ALL);
fprintf(stderr, "libcurl version: %s\n", curl_version());
// 构造要发送的 HTTP Header 链表
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "User-Agent: Ciallo/0.7.21");
headers = curl_slist_append(headers, "Content-Type: text/plain");
// POST 数据
const char post_data[] = "Ciallo~(∠·ω< )⌒★";
// 创建请求
CURL *handle = curl_easy_init();
curl_easy_setopt(handle, CURLOPT_URL, URL); // 请求 URL
curl_easy_setopt(handle, CURLOPT_HTTPHEADER, headers); // 请求标头
curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, 1L); // 跟随 3xx 重定向
curl_easy_setopt(handle, CURLOPT_POST, 1L); // POST
curl_easy_setopt(handle, CURLOPT_POSTFIELDS, post_data); // POST 数据
// recv_cb 的 userdata 参数
curl_easy_setopt(handle, CURLOPT_WRITEDATA, stdout);
// 数据接收 callback
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, recv_cb);
CURLcode curlcode = curl_easy_perform(handle);
if (curlcode == CURLE_OK) {
long httpcode;
curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &httpcode);
fprintf(stderr, "HTTP response status %ld\n", httpcode);
} else {
fprintf(stderr, "libcurl request error: %s (%d)\n",
curl_easy_strerror(curlcode), curlcode);
}
curl_easy_cleanup(handle);
handle = NULL;
curl_slist_free_all(headers);
headers = NULL;
curl_global_cleanup();
}