c用libcurl库实现https client实现get、post、文件上传、文件下载

c用libcurl库实现https client实现get、post、文件上传、文件下载


版本说明

版本 作者 日期 备注
0.1 loon 2019.4.2 初稿

目录


整理自: http://www.mamicode.com/info-detail-2018823.html

libcurl官网:https://curl.haxx.se/libcurl/

libcurl下载页面:https://curl.haxx.se/download.html

一、LibCurl基本编程框架

libcurl是一个跨平台的网络协议库,支持http, https,ftp, gopher, telnet, dict, file, 和ldap 协议。libcurl同样支持HTTPS证书授权,HTTP POST,HTTP PUT, FTP 上传, HTTP基本表单上传,代理,cookies,和用户认证。在基于LibCurl的程序里,主要采用callbackfunction (回调函数)的形式完成传输任务,用户在启动传输前设置好各类参数和回调函数,当满足条件时libcurl将调用用户的回调函数实现特定功能。下面是利用libcurl完成传输任务的流程:

    1. 调用curl_global_init()初始化libcurl
    1. 调用curl_easy_init()函数得到 easyinterface型指针
    1. 调用curl_easy_setopt()设置传输选项
    1. 根据curl_easy_setopt()设置的传输选项,实现回调函数以完成用户特定任务
    1. 调用curl_easy_perform()函数完成传输任务
    1. 调用curl_easy_cleanup()释放内存

在整过过程中设置curl_easy_setopt()参数是最关键的,几乎所有的libcurl程序都要使用它。

二、一些基本的函数

1. CURLcode curl_global_init(long flags);

描述:

这个函数只能用一次。(其实在调用curl_global_cleanup函数后仍然可再用)

如果这个函数在curl_easy_init函数调用时还没调用,它讲由libcurl库自动调用,所以多线程下最好主动调用该函数以防止在线程中curl_easy_init时多次调用。

注意:虽然libcurl是线程安全的,但curl_global_init是不能保证线程安全的,所以不要在每个线程中都调用curl_global_init,应该将该函数的调用放在主线程中。

参数:flags

CURL_GLOBAL_ALL //初始化所有的可能的调用。

CURL_GLOBAL_SSL //初始化支持安全套接字层。

CURL_GLOBAL_WIN32 //初始化win32套接字库。

CURL_GLOBAL_NOTHING//没有额外的初始化。

2. void curl_global_cleanup(void);

描述:在结束libcurl使用的时候,用来对curl_global_init做的工作清理。类似于close的函数。

注意:虽然libcurl是线程安全的,但curl_global_cleanup是不能保证线程安全的,所以不要在每个线程中都调用curl_global_init,应该将该函数的调用放在主线程中。

3. char *curl_version( );

描述: 打印当前libcurl库的版本。

4. CURL *curl_easy_init( );

描述:

curl_easy_init用来初始化一个CURL的指针(有些像返回FILE类型的指针一样). 相应的在调用结束时要用curl_easy_cleanup函数清理.

一般curl_easy_init意味着一个会话的开始. 它会返回一个easy_handle(CURL*对象), 一般都用在easy系列的函数中.

5. void curl_easy_cleanup(CURL *handle);

描述:

这个调用用来结束一个会话.与curl_easy_init配合着用.

参数:

CURL类型的指针.

6. CURLcode curl_easy_setopt(CURL *handle, CURLoption option,parameter);

描述: 这个函数最重要了.几乎所有的curl 程序都要频繁的使用它.它告诉curl库.程序将有如何的行为. 比如要查看一个网页的html代码等.(这个函数有些像ioctl函数)参数:

1 CURL类型的指针

2 各种CURLoption类型的选项.(都在curl.h库里有定义,man 也可以查看到)

3 parameter 这个参数既可以是个函数的指针,也可以是某个对象的指针,也可以是个long型的变量.它用什么这取决于第二个参数.

CURLoption 这个参数的取值很多.具体的可以查看man手册.

7. CURLcode curl_easy_perform(CURL *handle);

描述:这个函数在初始化CURL类型的指针以及curl_easy_setopt完成后调用. 就像字面的意思所说perform就像是个舞台.让我们设置的

option 运作起来.参数:

CURL类型的指针.

三、curl_easy_setopt函数部分选项介绍

本节主要介绍curl_easy_setopt中跟http相关的参数。该函数是curl中非常重要的函数,curl所有设置都是在该函数中完成的,该函数的设置选项众多,注意本节的阐述的只是部分常见选项。

1. CURLOPT_URL

设置访问URL

2. CURLOPT_WRITEFUNCTION,CURLOPT_WRITEDATA

回调函数原型为:size_t function(void *ptr, size_t size, size_t nmemb, void *stream);函数将在libcurl接收到数据后被调用,因此函数多做数据保存的功能,如处理下载文件。CURLOPT_WRITEDATA用于表明CURLOPT_WRITEFUNCTION函数中的stream指针的来源。

如果你没有通过CURLOPT_WRITEFUNCTION属性给easy handle设置回调函数,libcurl会提供一个默认的回调函数,它只是简单的将接收到的数据打印到标准输出。你也可以通过CURLOPT_WRITEDATA属性给默认回调函数传递一个已经打开的文件指针,用于将数据输出到文件里。

3. CURLOPT_HEADERFUNCTION,CURLOPT_HEADERDATA

回调函数原型为 size_tfunction( void *ptr, size_t size,size_t nmemb, void *stream); libcurl一旦接收到http 头部数据后将调用该函数。CURLOPT_WRITEDATA传递指针给libcurl,该指针表明CURLOPT_HEADERFUNCTION函数的stream指针的来源。

4. CURLOPT_READFUNCTIONCURLOPT_READDATA

libCurl需要读取数据传递给远程主机时将调用CURLOPT_READFUNCTION指定的函数,函数原型是:size_tfunction(void *ptr, size_t size, size_t nmemb,void *stream). CURLOPT_READDATA 表明CURLOPT_READFUNCTION函数原型中的stream指针来源。

5. CURLOPT_NOPROGRESS,CURLOPT_PROGRESSFUNCTION,CURLOPT_PROGRESSDATA

跟数据传输进度相关的参数。CURLOPT_PROGRESSFUNCTION指定的函数正常情况下每秒被libcurl调用一次,为了使CURLOPT_PROGRESSFUNCTION被调用,CURLOPT_NOPROGRESS必须被设置为false,CURLOPT_PROGRESSDATA指定的参数将作为CURLOPT_PROGRESSFUNCTION指定函数的第一个参数

6. CURLOPT_TIMEOUT,CURLOPT_CONNECTIONTIMEOUT:

CURLOPT_TIMEOUT 由于设置传输时间,CURLOPT_CONNECTIONTIMEOUT 设置连接等待时间

7. CURLOPT_FOLLOWLOCATION

设置重定位URL

8. CURLOPT_RANGE: CURLOPT_RESUME_FROM:

断点续传相关设置。CURLOPT_RANGE指定char *参数传递给libcurl,用于指明http域的RANGE头域,例如:

表示头500个字节:bytes=0-499

表示第二个500字节:bytes=500-999

表示最后500个字节:bytes=-500

表示500字节以后的范围:bytes=500-

第一个和最后一个字节:bytes=0-0,-1

同时指定几个范围:bytes=500-600,601-999

CURLOPT_RESUME_FROM 传递一个long参数给libcurl,指定你希望开始传递的偏移量。

四、curl_easy_perform函数说明(error 状态码)

该函数是完成curl_easy_setopt指定的所有选项,本节重点介绍curl_easy_perform的返回值。返回0意味一切ok,非0代表错误发生。主要错误码说明:

1. CURLE_OK

任务完成一切都好

2. CURLE_UNSUPPORTED_PROTOCOL

不支持的协议,由URL的头部指定

3. CURLE_COULDNT_CONNECT

不能连接到remote 主机或者代理

4. CURLE_REMOTE_ACCESS_DENIED

访问被拒绝

5. CURLE_HTTP_RETURNED_ERROR

Http返回错误

6. CURLE_READ_ERROR

读本地文件错误

要获取详细的错误描述字符串,可以通过const char*curl_easy_strerror(CURLcode errornum )这个函数取得.

五、http与https的区别

Http是明文发送,任何人都可以拦截并读取内容

Https是加密传输协议,用它传输的内容都是加密过的,https是http的扩展,其安全基础是SSL协议 #协议层理解,多了一层对数据的加密,加密方式是SSL加密,应该是公钥和私钥的理解。

六、具体示例

1. POST:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>

int main(void)
{
    CURL *curl;
    CURLcode res;

    curl_global_init(CURL_GLOBAL_ALL);
    /* get a curl handle */
    curl = curl_easy_init();

    if (!curl) {
        return -1;
    }

    /*设置easy handle属性*/
    /* specify URL */
    curl_easy_setopt(curl, CURLOPT_URL, url);

    /* specify we want to POST data */
    curl_easy_setopt(curl, CURLOPT_POST, 1L);
    /* Set the expected POST size */
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)datelen);
    /* Set the expected POST data */
    curl_easy_setopt(curl,CURLOPT_POSTFIELDS, (char *)postdata);

    curl_easy_setopt (curl,CURLOPT_SSL_VERIFYPEER, 0L);
    curl_easy_setopt (curl,CURLOPT_SSL_VERIFYHOST, 0L);
    curl_easy_setopt (curl,CURLOPT_SSLCERT,"client.crt");
    curl_easy_setopt (curl, CURLOPT_SSLCERTTYPE, "PEM");
    curl_easy_setopt (curl, CURLOPT_SSLKEY,"client.key");
    curl_easy_setopt (curl, CURLOPT_SSLKEYTYPE,"PEM");

    curl_easy_setopt (curl,CURLOPT_TIMEOUT, 60L);
    curl_easy_setopt (curl,CURLOPT_CONNECTTIMEOUT, 10L);

    /*执行数据请求*/
    res = curl_easy_perform(curl);
    if(res !=CURLE_OK)
    {
        fprintf(stderr, "curl_easy_perform() failed: %s\n",
            curl_easy_strerror(res));
    }

    // 释放资源
    curl_easy_cleanup(curl);
    curl_global_cleanup();

    return 0;
}

2. GET:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>

struct MemoryStruct {
    char *memory;
    size_t size;
};

static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
    size_t realsize = size * nmemb;
    struct MemoryStruct *mem = (struct MemoryStruct *)userp;

    mem->memory = realloc(mem->memory, mem->size + realsize + 1);
    if(mem->memory == NULL)
    {
        /* out of memory! */
        printf("not enough memory (realloc returned NULL)\n");
        return 0;
    }

    memcpy(&(mem->memory[mem->size]), contents, realsize);
    mem->size += realsize;
    mem->memory[mem->size] = 0;

    return realsize;
}



int main(void)
{
    CURL *curl = NULL;
    CURLcode res;
    struct MemoryStruct chunk;

    chunk.memory = malloc(1);  /* will be grown as needed by the realloc above */
    chunk.size = 0;    /* no data at this point */
    
    curl_global_init(CURL_GLOBAL_ALL);
    /* get a curl handle */
    curl = curl_easy_init();
    if (!curl)
    {
        return -1;
    }

    /*设置easy handle属性*/
    /* specify URL */
    curl_easy_setopt (curl,CURLOPT_URL, url);
    /* Define our callback to get called when there‘s data to be written */
    curl_easy_setopt (curl,CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
    /* Set a pointer to our struct to pass to the callback */
    curl_easy_setopt(curl,CURLOPT_WRITEDATA, (void *)&chunk);
    
    /* set commom option */
    curl_easy_setopt (curl,CURLOPT_SSL_VERIFYPEER, 0L);
    curl_easy_setopt (curl,CURLOPT_SSL_VERIFYHOST, 0L);

    curl_easy_setopt (curl,CURLOPT_SSLCERT,"client.crt");
    curl_easy_setopt (curl, CURLOPT_SSLCERTTYPE, "PEM");
    curl_easy_setopt (curl, CURLOPT_SSLKEY,"client.key");
    curl_easy_setopt (curl, CURLOPT_SSLKEYTYPE,"PEM");

    curl_easy_setopt (curl,CURLOPT_TIMEOUT, 60L);
    curl_easy_setopt (curl,CURLOPT_CONNECTTIMEOUT, 10L);

    /* get verbose debug output please */
    /*执行数据请求*/
    res = curl_easy_perform(curl);
    if (res !=CURLE_OK)
    {
        fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(res));
    }   

    // 释放资源
    free(chunk.memory);
    curl_easy_cleanup(curl);
    curl_global_cleanup();

    return 0;
}

3. 上传文件:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>

//这个函数是为了符合CURLOPT_READFUNCTION而构造的
//数据上传时使用
static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *stream)
{
    size_t retcode;
    curl_off_t nread;
    
    /* in real-world cases, this would probably get this data differently as this fread() stuff is exactly what the library already would do by default internally */
    retcode = fread(ptr, size, nmemb, stream);
    nread = (curl_off_t)retcode;
    
    fprintf(stderr, "*** We read %" CURL_FORMAT_CURL_OFF_T" bytes from file\n", nread);

    return retcode;
}

int main(void)
{
    CURL *curl;
    CURLcode res;
    FILE * fstream;
    struct stat file_info;

    /* get the file size of the local file */
    stat(file, &file_info);
    fstream = fopen(file, "rb");
    curl_global_init(CURL_GLOBAL_ALL);
    
    /* get a curl handle */
    curl = curl_easy_init();
    if (!curl)
    {
        return -1;
    }

    /*设置easy handle属性*/
    /* specify URL */
    curl_easy_setopt(curl, CURLOPT_URL, url);
    /* we want to use our own read function */
    curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);
    /* which file to upload */
    curl_easy_setopt(curl, CURLOPT_READDATA, (void *) fstream);
    /* enable "uploading" */
    curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
    /* Set the size of the file to upload (optional) */
    curl_easy_setopt(curl,CURLOPT_INFILESIZE_LARGE, (curl_off_t)file_info.st_size);
    
    /* set commom option */
    curl_easy_setopt (curl,CURLOPT_SSL_VERIFYPEER, 0L);
    curl_easy_setopt (curl,CURLOPT_SSL_VERIFYHOST, 0L);
    curl_easy_setopt (curl,CURLOPT_SSLCERT,"client.crt");
    curl_easy_setopt (curl, CURLOPT_SSLCERTTYPE, "PEM");
    curl_easy_setopt (curl, CURLOPT_SSLKEY,"client.key");
    curl_easy_setopt (curl, CURLOPT_SSLKEYTYPE,"PEM");

    curl_easy_setopt (curl,CURLOPT_TIMEOUT, 60L);
    curl_easy_setopt (curl,CURLOPT_CONNECTTIMEOUT, 10L);
    /* get verbose debug output please */

    /*执行数据请求*/
    res = curl_easy_perform(curl);
    if (res !=CURLE_OK)
    {
        fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
    }   

    // 释放资源
    if(fstream)
        fclose(fstream);
    curl_easy_cleanup(curl);
    curl_global_cleanup();

    return 0;
}

4. 下载文件:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>

////这个函数是为了符合CURLOPT_WRITEFUNCTION而构造的
//完成数据保存功能
struct FtpFile {
    const char *filename;
    FILE *stream;
};

static size_t my_fwrite(void *buffer, size_t size, size_t nmemb, void *stream)
{
    struct FtpFile *out = (struct FtpFile *)stream;
    if(out && !out->stream)
    {
        /* open file for writing */
        out->stream = fopen(out->filename, "wb");
        if(!out->stream)
            return -1; /* failure, can‘t open file to write */
    }

    return fwrite(buffer, size, nmemb, out->stream);
}

int main(void)
{
    CURL *curl;
    CURLcode res;
    struct FtpFile ftpfile;
    curl_global_init(CURL_GLOBAL_ALL);
    /* get a curl handle */
    curl = curl_easy_init();
    if (!curl)
    {
        return -1;
    }

    /*设置easy handle属性*/
    /* specify URL */
    curl_easy_setopt(curl, CURLOPT_URL, url);
    /* Define our callback to get called when there‘s data to be written */
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_fwrite);
    /* Set a pointer to our struct to pass to the callback */
    curl_easy_setopt(curl,CURLOPT_WRITEDATA, &ftpfile);
    /* set commomoption */
    curl_easy_setopt (curl,CURLOPT_SSL_VERIFYPEER, 0L);
    curl_easy_setopt (curl,CURLOPT_SSL_VERIFYHOST, 0L);
    curl_easy_setopt (curl,CURLOPT_SSLCERT,"client.crt");
    curl_easy_setopt (curl, CURLOPT_SSLCERTTYPE, "PEM");
    curl_easy_setopt (curl, CURLOPT_SSLKEY,"client.key");
    curl_easy_setopt (curl, CURLOPT_SSLKEYTYPE,"PEM");

    curl_easy_setopt (curl,CURLOPT_TIMEOUT, 60L);
    curl_easy_setopt (curl,CURLOPT_CONNECTTIMEOUT, 10L);
    /* get verbose debug output please */
 
    /*执行数据请求*/
    res = curl_easy_perform(curl);
    if (res !=CURLE_OK)
    {
        fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
    }
    
    // 释放资源
    if(ftpfile.stream)
        fclose(ftpfile.stream); /* close the local file */
    curl_easy_cleanup(curl);
    curl_global_cleanup();

    return 0;
}
发布了119 篇原创文章 · 获赞 138 · 访问量 19万+

猜你喜欢

转载自blog.csdn.net/weixin_39510813/article/details/88978941