三方库编译笔记

libcurl

libcurl主要功能是用不同的协议连接和沟通不同的服务器,用做客户端。
libcurl当前支持http, https, ftp, gopher, telnet, dict, file, 和ldap 协议。

  • 下载地址:https://curl.haxx.se/download.html
  • linux编译:标准三步曲

    ./configure
    make
    make install
    
  • win32编译

源码根目录下有个winbuild目录,cd到此目录,编译方法详见BUILD.WINDOWS.txt
打开VS命令提示符,输入如下命令:

nmake /f Makefile.vc mode=static VC=14 MACHINE=x64 DEBUG=no ENABLE_IDN=no

note:此处将ENABLE_IDN设为no,因为需要windows vista以后版本,不兼容xp

编译无错误,会在根目录下的builds下生成了include、lib、bin

  • 使用
    包含头文件#include <curl/curl.h>
    如果是使用静态库,需要在包含此头文件前加上CURL_STATICLIB宏定义

  • 示例代码:http请求封装

// curl_wrap.h
#ifndef CURL_WRAP_H_INCLUDED
#define CURL_WRAP_H_INCLUDED

#define CURL_STATICLIB
#include <curl/curl.h>

#define HTTP_GET    0
#define HTTP_POST   1
#define HTTP_PUT    2
#define HTTP_DELETE 3

size_t default_write_cb(char *buf, size_t size, size_t cnt, void *userdata);
int curl(int method, char* url, char *headerv[] = NULL, int headerc = 0, char *content = NULL,
         curl_write_callback write_cb = default_write_cb, void* userdata = NULL, long timeout = 0L);

#endif // CURL_WRAP_H_INCLUDED
// curl_wrap.c
#include "curl_wrap.h"

size_t default_write_cb(char *buf, size_t size, size_t cnt, void *userdata){
    return size*cnt;
}

int curl(int method, char* url, char *headerv[], int headerc, char *content,
         curl_write_callback write_cb, void* userdata, long timeout){

    CURL* handle = curl_easy_init();

    switch (method)
    {
    case HTTP_GET:
        curl_easy_setopt(handle, CURLOPT_HTTPGET, 1L);
        break;
    case HTTP_POST:
        curl_easy_setopt(handle, CURLOPT_HTTPPOST, 1L);
        break;
    case HTTP_PUT:
        curl_easy_setopt(handle, CURLOPT_CUSTOMREQUEST, "put");
        break;
    case HTTP_DELETE:
        curl_easy_setopt(handle, CURLOPT_CUSTOMREQUEST, "delete");
        break;
    default:
        break;
    }

    curl_easy_setopt(handle, CURLOPT_URL, url);
    struct curl_slist *headers = NULL;
    if (headerc > 0){
        for (int i = 0; i < headerc; ++i){
            headers = curl_slist_append(headers, headerv[i]);
        }
        curl_easy_setopt(handle, CURLOPT_HTTPHEADER, headers);
    }

    if (content){
        curl_easy_setopt(handle, CURLOPT_POSTFIELDS, content);
        curl_easy_setopt(handle, CURLOPT_POSTFIELDSIZE, strlen(content));
    }

    curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, write_cb);
    curl_easy_setopt(handle, CURLOPT_WRITEDATA, userdata);
    if (timeout != 0)
        curl_easy_setopt(handle, CURLOPT_TIMEOUT, timeout); 

    int ret = curl_easy_perform(handle);
    if (ret != CURLE_OK){
        loge("curl_easy_perform failed:%s", curl_easy_strerror(ret));
        return ERR;
    }

    if (headers){
        curl_slist_free_all(headers);
    }
    curl_easy_cleanup(handle);
    return OK;
}

猜你喜欢

转载自blog.csdn.net/GG_SiMiDa/article/details/80536857
今日推荐