天天看点

libcurl 介绍

本文主要介绍 libcurl 的编程步骤。

curl 是利用 URL 语法在命令行方式下工作的开源文件传输工具。

可以在官方下载地址去下载curl

libcurl 编程指南 里详细介绍了 libcurl 的用法。

libcurl 的文档非常丰富,而且有很多 libcurl 使用的例子 可供参考。

另外,可以下载 everything-curl,这是一个 curl 详尽的使用文档。

#include "curl/curl.h"
#include <fstream>

// 写入的回调函数
size_t write_data(void *buffer, size_t size, size_t nmemb, void *userp)
{
    reinterpret_cast<std::ofstream*>(userp)->write(reinterpret_cast<char*>(buffer), size * nmemb);
    return size * nmemb;
}

int main(void)
{
    // 调用任何 curl 函数之前,必须先调用 curl_global_init 初始化 curl 库,
    // 详情参见 curl_global_init 注释
    // 一般情况下使用参数 CURL_GLOBAL_ALL 初始化所有可用的模块
    if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK)
    {
        return -;
    }

    // 为了使用 easy interface,必须首先创建一个 easy handle。
    CURL* easyHandle = curl_easy_init();
    if (NULL == easyHandle)
    {
        return -;
    }

    // 通过调用 curl_easy_setopt 设置可选项
    // 设置网址
    const char* url = "https://www.gitbook.com/download/pdf/book/bagder/everything-curl";
    curl_easy_setopt(easyHandle, CURLOPT_URL, url);
    // 设置回调函数
    curl_easy_setopt(easyHandle, CURLOPT_WRITEFUNCTION, write_data);
    // 设置回调参数,在回调函数调用时,该参数作为回调函数的第四个参数原封不动的传给回调函数
    const char* savePath = "D:\\test.pdf";
    std::ofstream fout(savePath, std::ofstream::app | std::ofstream::out | std::ofstream::binary);
    if (!fout)
    {
        return ;
    }
    curl_easy_setopt(easyHandle, CURLOPT_WRITEDATA, &fout);

    // 执行请求
    CURLcode ret = curl_easy_perform(easyHandle);
    if (ret != CURLE_OK)
    {
        fout.close();
        return -;
    }

    fout.close();
    return ;
}