一、libcurl简介
libcurl是一个跨平台的网络协议库,支持http, https, ftp, gopher, telnet, dict, file, 和ldap 协议。libcurl同样支持HTTPS证书授权,HTTP POST, HTTP PUT, FTP 上传, HTTP基本表单上传,代理,cookies,和用户认证。
libcurl的官网http://curl.haxx.se/
库下载https://github.com/curl/curl/releases/tag/curl-7_71_1
拿到压缩包后进行解压,一般来说这些库都会有很多文件,先去看README,doc, INSTALL,然后慢慢看相关的文件,找到编译,安装的命令,或许还有配置的命令。
./configure --prefix=$PWD/_install
更改安装位置为当前目录的_install文件下,_install文件会自动创建,这些配置需要针对具体情况而言,不是每个库都这样
./configure --prefix=$PWD/_install --host arm-linux
这里的--host 为指定编译工具,默认应该是使用gcc,这次在乌班图的平台下就不需要了
sudo make
sudo make install
到这一步便会出现先前的_install了
准备一份测试代码,下面有提及到,进行编译测试。
#include <stdio.h>
#include <curl/curl.h>
//因为默认C只有0,1,int没有bool,true和false
#define true 1
#define false 0
typedef unsigned int bool;
bool getUrl(char *filename)
{
CURL *curl;
CURLcode res;
FILE *fp;
if ((fp = fopen(filename, "w")) == NULL) // 返回结果用文件存储
return false;
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Accept: Agent-007");
curl = curl_easy_init(); // 初始化
if (curl)
{
//curl_easy_setopt(curl, CURLOPT_PROXY, "10.99.60.201:8080");// 代理
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);// 改协议头
curl_easy_setopt(curl, CURLOPT_URL,"http://www.baidu.com");
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); //将返回的http头输出到fp指向的文件
curl_easy_setopt(curl, CURLOPT_HEADERDATA, fp); //将返回的html主体数据输出到fp指向的文件
res = curl_easy_perform(curl); // 执行
if (res != 0) {
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
}
fclose(fp);
return true;
}
}
bool postUrl(char *filename)
{
CURL *curl;
CURLcode res;
FILE *fp;
if ((fp = fopen(filename, "w")) == NULL)
return false;
curl = curl_easy_init();
if (curl)
{
curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "/tmp/cookie.txt"); // 指定cookie文件
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "&logintype=uid&u=xieyan&psw=xxx86"); // 指定post内容
//curl_easy_setopt(curl, CURLOPT_PROXY, "10.99.60.201:8080");
curl_easy_setopt(curl, CURLOPT_URL, " http://mail.sina.com.cn/cgi-bin/login.cgi "); // 指定url
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
fclose(fp);
return true;
}
int main(void)
{
getUrl("/tmp/get.html");
postUrl("/tmp/post.html");
}
gcc demo1.c -I ./curl-7.71.1/_install/include/ -L ./curl-7.71.1/_install/lib/ -lcurl
运行后发现出现错误,想到应该是动态库的路径问题
./a.out: error while loading shared libraries: libcurl.so.4: cannot open shared object file: No such file or directory
二、libcurl的使用
调用curl_global_init()初始化libcurl
调用curl_easy_init()函数得到 easy interface型指针
调用curl_easy_setopt()设置传输选项
根据curl_easy_setopt()设置的传输选项,实现回调函数以完成用户特定任务
调用curl_easy_perform()函数完成传输任务
调用curl_easy_cleanup()释放内存
三、树莓派上安装了curl出现no space left on device错误
sudo raspi-config
然后重启,就可解决了。