结构体数组实现 post表单
struct form_field {
name
value
}
struct form_field fields[] = {
{"orderState", "1" },
{"orderDate", "2023-07-26 14:44:14" }
// 可继续添加其他字段
};
// 发送HTTP POST请求,提交form-data数据
int sendHttpPostForm(const char *url, struct form_field *fields, int field_count, char *response_buffer) {
// 初始化CURL库
curl_global_init(CURL_GLOBAL_ALL);
// 创建一个CURL句柄
CURL *curl = curl_easy_init();
if (curl) {
// 设置请求的URL
curl_easy_setopt(curl, CURLOPT_URL, url);
// 设置总超时时间为10秒
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 1);
// 设置连接建立的超时时间为5秒
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 1);
// 设置POST请求
curl_easy_setopt(curl, CURLOPT_POST, 1L);
// 设置form-data数据
struct curl_httppost *formpost = NULL;
struct curl_httppost *lastptr = NULL;
// 添加form-data字段
for (int i = 0; i < field_count; i++) {
curl_formadd(&formpost, &lastptr,
CURLFORM_COPYNAME, fields[i].name,
CURLFORM_COPYCONTENTS, fields[i].value,
CURLFORM_END);
}
// 设置form-data数据
curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
// 设置响应处理函数
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
// 设置响应数据保存的缓冲区
curl_easy_setopt(curl, CURLOPT_WRITEDATA, response_buffer);
// 设置用户代理
curl_easy_setopt(curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36");
// 执行请求
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
curl_formfree(formpost);
curl_easy_cleanup(curl);
curl_global_cleanup();
return -1;
}
// 清理资源
curl_formfree(formpost);
curl_easy_cleanup(curl);
} else {
curl_global_cleanup();
return -1;
}
// 清理CURL库
curl_global_cleanup();
return 0;
}