还在苦苦敲代码开发APP?你out啦! 试试积木搭建APP吧~

libcurl的使用总结

来源:个人博客     2016-04-15 10:19:19    人气:     我有话说( 0 人参与)

最近的项目中由于要在C++代码中调用PHP的URL,所以不得不借助libcurl这个库,由于第一次用,所以很多地方很是纠结,特此写在这里,方便给同...

最近的项目中由于要在C++代码中调用PHP的URL,所以不得不借助libcurl这个库,由于第一次用,所以很多地方很是纠结,特此写在这里,方便给同样刚入门的朋友指引。

一.下载安装
    1.到http://curl.haxx.se/download.html上下载最新版本,由于公司的机器安装rpm有依赖关系,所以直接下载了source
    2.编译。解压后进入curl的目录,直接执行 make all 就行。
    3.等待编译结束后,可以查看目录结构。
        curl/include/curl : 头文件目录 (一般只要包含curl.h即可)
        curl/lib/.lib/      : lib文件目录(有libcurl.a和libcurl.so,注意,如果这两个文件在同一目录下,-lcurl默认是链接.so滴)

二.函数简要说明
在基于LibCurl的程序里,主要采用callback function (回调函数)的形式完成传输任务,用户在启动传输前设置好各类参数和回调函数,当满足条件时libcurl将调用用户的回调函数实现特定功能。下面是利用libcurl完成传输任务的流程:

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

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

1)CURLcode curl_global_init(long flags);
描述:
这个函数只能用一次。(其实在调用curl_global_cleanup 函数后仍然可再用)
如果这个函数在curl_easy_init函数调用时还没调用,它讲由libcurl库自动完成。
参数: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的函数。

3.char *curl_version( );
描述: 打印当前libcurl库的版本。

4)CURL *curl_easy_init( );
描述:
curl_easy_init用来初始化一个CURL的指针(有些像返回FILE类型的指针一样). 相应的在调用结束时要用curl_easy_cleanup函数清理.
一般curl_easy_init意味着一个会话的开始. 它的返回值一般都用在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类型的指针.

三.重要函数详解
1)curl_easy_setopt函数介绍

本节主要介绍curl_easy_setopt中跟http相关的参数。注意本节的阐述都是以libcurl作为主体,其它为客体来阐述的。
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指针的来源。
3.      CURLOPT_HEADERFUNCTION,CURLOPT_HEADERDATA
回调函数原型为 size_t function( void *ptr, size_t size,size_t nmemb, void *stream); libcurl一旦接收到http 头部数据后将调用该函数。CURLOPT_WRITEDATA 传递指针给libcurl,该指针表明CURLOPT_HEADERFUNCTION 函数的stream指针的来源。
4.       CURLOPT_READFUNCTION CURLOPT_READDATA
libCurl需要读取数据传递给远程主机时将调用CURLOPT_READFUNCTION指定的函数,函数原型是:size_t function(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
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,指定你希望开始传递的
偏移量。
2)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
    读本地文件错误
 

以下主要是一些使用示例,由于部分代码是来源网上,原作者已经无法考证,所以如有原作者看到,可以告诉我,我给注明~

另:文末附有所有代码的打包下载,均在suse 10下编译运行通过

1.下载文件到本地

/*==============================================
#  Author:          DanteZhu – http://www.vimer.cn
#  Email:           dantezhu@vip.qq.com
#  FileName:        test_download.cpp
#  Version:         1.0
#  LastChange:      2010-03-09 14:20:44
#  Description:     
#  History:         
============================================*/
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include “curl/curl.h”
using namespace std;
static char errorBuffer[CURL_ERROR_SIZE];
static int writer(char *, size_t, size_t, string *);
static bool init(CURL *&, char *,string *);
int main()
{
    CURL *conn = NULL;
    CURLcode code;
    string buffer;
    curl_global_init(CURL_GLOBAL_DEFAULT);
    char* url=“172.16.211.50/cc2/cc/getfile.php”;
    if (!init(conn,url,&buffer ))
    {
        fprintf(stderr, “Connection initializion failed\n”);
        exit(EXIT_FAILURE);
    }
    code = curl_easy_perform(conn);
    if (code != CURLE_OK)
    {
        fprintf(stderr, “Failed to get ‘%s’ [%s]\n”, url, errorBuffer);
        exit(EXIT_FAILURE);
    }
    FILE * file = fopen(“1.gif”,“wb”);
    fseek(file,0,SEEK_SET);
    fwrite(buffer.c_str(),1,buffer.size(),file);
    fclose(file);
    curl_easy_cleanup(conn);
    printf(“%s\n”,buffer.c_str());
    return 0;
}
static bool init(CURL *&conn, char *url,string *p_buffer)
{
    CURLcode code;
    conn = curl_easy_init();
    if (conn == NULL)
    {
        fprintf(stderr, “Failed to create CURL connection\n”);
        exit(EXIT_FAILURE);
    }
    code = curl_easy_setopt(conn, CURLOPT_ERRORBUFFER, errorBuffer);
    if (code != CURLE_OK)
    {
        fprintf(stderr, “Failed to set error buffer [%d]\n”, code);
        return false;
    }
    code = curl_easy_setopt(conn, CURLOPT_URL, url);
    if (code != CURLE_OK)
    {
        fprintf(stderr, “Failed to set URL [%s]\n”, errorBuffer);
        return false;
    }
    code = curl_easy_setopt(conn, CURLOPT_FOLLOWLOCATION, 1);
    if (code != CURLE_OK)
    {
        fprintf(stderr, “Failed to set redirect option [%s]\n”, errorBuffer);
        return false;
    }
    code = curl_easy_setopt(conn, CURLOPT_WRITEFUNCTION, writer);
    if (code != CURLE_OK)
    {
        fprintf(stderr, “Failed to set writer [%s]\n”, errorBuffer);
        return false;
    }
    code = curl_easy_setopt(conn, CURLOPT_WRITEDATA, p_buffer);
    if (code != CURLE_OK)
    {
        fprintf(stderr, “Failed to set write data [%s]\n”, errorBuffer);
        return false;
    }
    return true;
}
static int writer(char *data, size_t size, size_t nmemb, string *writerData)
{
    unsigned long sizes = size * nmemb;
    if (writerData == NULL) return 0;
    writerData->append(data, sizes);
    return sizes;
}

2.通过multipart/form-data方式上传文件模仿的HTML代码:

<html>
    <head>
        <meta http-equiv=content-type content=“text/html;charset=gb2312″>
        <title>File Upload</title>
    </head>
<body>
    <form action=“/?fileupload” method=“post” id=“uplodfile” name=“uploadfile”  enctype=“multipart/form-data” >
        <input type=“file” id=“file” name=“upload” style=“width:300px”>
        <input name=“submit” type=“submit” value=“OK” >
    </form>
</body>
</html>

C代码:

/*=============================================
#  Author:          DanteZhu – http://www.vimer.cn
#  Email:           dantezhu@vip.qq.com
#  FileName:        test.cpp
#  Version:         1.0
#  LastChange:      2010-03-08 20:23:23
#  Description:     
#  History:         
============================================*/
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include “curl/curl.h”
using namespace std;
#define MAX_BUFF_LEN 1048576 /*1M*/
#define POST_URL “172.16.211.50/cc2/cc/setfile.php”
int check_file_existed(char *filename)
{
    struct stat st;
     return (stat( filename, &st )==0 && S_ISREG(st.st_mode));
}
int get_file_size(char *filename)
{
    int file_len = 0;
    int fd = 0;
    fd = open(filename, O_RDONLY);
    if(fd < 0)
    {
        perror(“open”);
        exit(-1);
    }
    file_len = lseek(fd, 0, SEEK_END);
    if(file_len < 0)
    {
        perror(“lseek”);
        exit(-1);
    }
    return file_len;
}
int http_post_file(const char *url, const char *filename)
{
    CURL *curl = NULL;
    CURLcode res;
    int timeout = 5;
    struct curl_httppost *post=NULL;
    struct curl_httppost *last=NULL;
    struct curl_slist *headerlist=NULL;
    if(filename == NULL || url == NULL)
        return -1;
    printf(“URL: %s\n”, url);
    printf(“filename: %s\n”, filename);
    /* Add simple file section */
    if( curl_formadd(&post, &last, CURLFORM_COPYNAME, “content”,
                CURLFORM_FILE, filename, CURLFORM_END) != 0)
    {
        fprintf(stderr, “curl_formadd error.\n”);
        goto out;
    }
    /* Fill in the submit field too, even if this is rarely needed */
    curl_formadd(&post, &last,
            CURLFORM_COPYNAME, “submit”,
            CURLFORM_COPYCONTENTS, “OK”,
            CURLFORM_END);
    //curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();
    if(curl == NULL)
    {
        fprintf(stderr, “curl_easy_init() error.\n”);
        goto out;
    }
    curl_easy_setopt(curl, CURLOPT_HEADER, 0);
    curl_easy_setopt(curl, CURLOPT_URL, url); /*Set URL*/
    curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 1);
    res = curl_easy_perform(curl);
    if(res != CURLE_OK)
    {
        fprintf(stderr, “curl_easy_perform[%d] error.\n”, res);
        goto out;
    }
    curl_easy_cleanup(curl);
out:
    curl_formfree(post);
    //curl_global_cleanup();
    return 0;
}
int main(int argc, char *argv[])
{
    char buff[MAX_BUFF_LEN]={0};
    //Check Argument
    //argv[1] upload filename
    if(argc != 2)
    {
        fprintf(stderr, “Usage: %s filename\n”, argv[0]);
        return 1;
    }
    //Check File Existed
    if(!check_file_existed(argv[1]))
    {
        fprintf(stderr, “File Not Existed.\n”);
        return 1;
    }
    //Check File Size
    if( get_file_size(argv[1]) >= MAX_BUFF_LEN)
    {
        fprintf(stderr, “File Size is Big!\n”);
        return 1;
    }
    //POST File
    http_post_file(POST_URL, argv[1]);
    return 0;
}

3)makefile的编写(注意链接的库,及库的顺序)

#=========================================
#  Author:          DanteZhu – http://www.vimer.cn
#  Email:           dantezhu@vip.qq.com
#  FileName:        makefile
#  Version:         1.0
#  LastChange:      2010-03-09 14:46:48
#  Description:     
#  History:         
#=========================================
CXX = g++
TARGET =  test_download test_post
C_FLAGS += -g -Wall
INC+=-I../include -I /home/dantezhu/curl-7.20.0/include/
LIB+=-L. -lcurl -lz -lrt -lcrypto -lssl
LIB_FLAGS = -pthread
all: $(TARGET)
test_download:  test_download.o
    $(CXX) -o $@ $^  $(LIB_FLAGS) $(LIB) $(C_FLAGS)
test_post:  test_post.o
    $(CXX) -o $@ $^  $(LIB_FLAGS) $(LIB) $(C_FLAGS)
.cpp.o:
    $(CXX) -c -o $*.o $(INC) $(C_FLAGS) $*.cpp
.cc.o:
    $(CXX) -c -o $*.o $(INC) $(C_FLAGS) $*.cc
clean:
    -rm -f *.o $(TARGET)

 

附:代码程序打包下载
 

版权属于:Vimer的程序世界

原文地址:http://www.vimer.cn?p=932

转载时必须以链接形式注明原始出处及本声明。

libcurl 使用 总结

本文源自互联网,采用知识共享署名-非商业性使用 4.0 国际许可协议进行许可,
版权归原作者,如有问题请联系service@tsingfun.com (编辑:admin)
分享到: