1. 什么是 libcurl

libcurl 是一个用 C 语言编写的开源的 URL 传输库,支持多种网络协议,如 HTTP、HTTPS、FTP 等。它可以用来实现各种网络任务,如发送 HTTP 请求、上传文件、下载文件等。它支持多种编程语言,如 C、C++、Python、Perl、PHP 等。

2. 使用 libcurl POST 数据

使用 libcurl 发送 POST 数据,首先要初始化一个 curl 句柄,然后设置 POST 数据,最后发送 POST 请求。具体步骤如下:

123456789
// 初始化一个curl句柄
CURL *curl = curl_easy_init();

// 设置POST数据
char *data = "name=John&age=20";
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);

// 设置请求URL
curl_easy_setopt(curl, CURLOPT_URL, "http://example.com/post");

// 发送POST请求
CURLcode res = curl_easy_perform(curl);

// 释放curl句柄
curl_easy_cleanup(curl);
C

3. 使用 libcurl 上传文件

使用 libcurl 上传文件,首先要初始化一个 curl 句柄,然后设置上传文件,最后发送 POST 请求。具体步骤如下:

1234567891011
// 初始化一个curl句柄
CURL *curl = curl_easy_init();

// 设置上传文件
struct curl_httppost *post = NULL;
struct curl_httppost *last = NULL;
curl_formadd(&post, &last, 
    CURLFORM_COPYNAME, "file",
    CURLFORM_FILE, "/path/to/file.txt",
    CURLFORM_END);

// 设置请求URL
curl_easy_setopt(curl, CURLOPT_URL, "http://example.com/upload");

// 设置POST数据
curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);

// 发送POST请求
CURLcode res = curl_easy_perform(curl);

// 释放curl句柄
curl_easy_cleanup(curl);
C