LibCurl使用和交叉编译
LibCurl使用和交叉编译
一、交叉编译openssl
LibCurl如果要启用ssl,需要先交叉编译openssl库以作为依赖。这里使用的是openssl-1.1.0l版本,交叉编译命令如下:
./Configure --prefix=../ --cross-compile-prefix=msdk-linux- linux-elf no-asm no-shared
make
直接编译完成后,LibCurl很可能找不到openssl库,因为它要寻找/lib文件夹和/include文件夹,所以要在openssl目录下执行
mkdir lib && cp -rf lib* ./lib
二、编译LibCurl
这里直接给出我交叉编译成功的配置
./configure --with-openssl=/data1/trunk/APP/framework/openssl/openssl-1.1.0l --disable-shared --enable-static --disable-dict --disable-ftp --disable-imap --disable-ldap --disable-ldaps --disable-pop3 --disable-proxy --disable-rtsp --disable-smtp --disable-telnet --disable-tftp --without-ca-bundle --without-librtmp --without-libssh2 --without-libpsl --prefix=$PWD/build --host=mips-linux CC=msdk-linux-gcc
之后直接执行
make && make install
.a库就会生成在./build目录下了。
三、使用LibCurl完成POST方式访问
直接上代码,使用libcurl以POST方式发送数据:
#include <stdio.h>
#include <curl/curl.h>
/**
* @fn timed_update_callback
* @brief 定时回调.
* @param OSI_VOID None
* @return None
*/
size_t timed_update_callback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t real_size = size * nmemb;
printf("%s\n", (char *)contents);
return real_size;
}
/**
* @fn TimedUpdate
* @brief .
* @param OSI_VOID None
* @return None
*/
int main(void)
{
CURL *curl;
CURLcode res;
struct curl_slist *cookies = NULL;
struct curl_slist *headers = NULL;
char* json_data ="{\"deviceSerial\":\"123456\",\"password\":\"xxx\"}"; // JSON格式的字符串
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
if(curl) {
//指定URL
curl_easy_setopt(curl, CURLOPT_URL, "http://10.13.98.36/iot/global/0-global/model/attribute/get/InfoMgr/DeviceLanguage");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, timed_update_callback);
//配置DNS选项
//curl_easy_setopt(curl, CURLOPT_DNS_CACHE_TIMEOUT, 0);
//curl_easy_setopt(curl, CURLOPT_DNS_SERVERS, "10.1.7.97"); //配置DNS服务器
//关闭证书验证
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
//http请求头
//headers = curl_slist_append(headers,"POST HTTP/1.1");
headers = curl_slist_append(headers,"Content-Type: application/x-www-form-urlencoded");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
//设置cookie
curl_easy_setopt(curl, CURLOPT_COOKIE, "olfsk=olfsk7257964002188215; pass=qwerty");
//使用Post方式发送数据
curl_easy_setopt(curl, CURLOPT_POST, 1); // post请求
curl_easy_setopt(curl, CURLOPT_POSTFIELDS,json_data); // 使用POST方式发送请求数据
//执行动作
res = curl_easy_perform(curl);
if(res != CURLE_OK)
{
//如果执行失败,报错
fprintf(stderr, "curl_easy_perform failed(%d): %s\n", res,curl_easy_strerror(res));
}
//释放资源
curl_easy_cleanup(curl);
}
curl_global_cleanup();
return 0;
}