今天得空来整理以前的笔记,看到了libcurl。稍微整理记录再加上顺带复习一下。
一、准备
- 下载
官网链接:https://curl.haxx.se/ - 编译三步走
cd curl
./buildconf
./configure
make
sudo make install
二、程序实例-发送一个post请求
#include <curl/curl.h>
// 注意参数 size * nmemb 是数据的总长度
size_t wirte_callback(char* ptr, size_t size, size_t nmemb, void* userdata)
{
char* buf = (char *)malloc(size * nmemb + 1);
memcpy(buf, ptr, size*nmemb);
buf[size*nmemb] = 0;
printf("recv data = %s\n", buf);
printf("*********************\n");
free(buf);
return size * nmemb;
}
int main()
{
CURLcode code = curl_global_init(CURL_GLOBAL_ALL);
if (code != CURLE_OK)
{
printf("global init err\n");
return -1;
}
// 初始化
CURL* curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_URL, "http://192.168.49.136:8081");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, wirte_callback); // 设置回调函数
curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
// 设置post提交方式
curl_easy_setopt(curl, CURLOPT_POST, 1);
// 设置post的数据
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "this is post data");
// 设置post的长度,如果是文本可以不用设置
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, sizeof("this is post data"));
// 发送
code = curl_easy_perform(curl);
if (code != CURLE_OK)
{
printf("perform err\n");
return -2;
}
curl_easy_cleanup(curl);
return 0;
}
三、总结
libcurl使用的还是比较简单的,主要的函数就是curl_easy_setopt()
,这个函数可以设置很多个数据,属性,方式等等。。。同时这个参数在官网有详细的说明,真的是太多了(鼠标拖了很久都没到底的那种,官网属性说明链接:https://curl.haxx.se/libcurl/c/curl_easy_setopt.html)。