Using libcurl in VC++

curl是瑞典curl组织开发的,Official Website:

Introduction

curl是一个基于命令行的应用工具,提供利用URL标准进行文件传输的功能。

目前已经支持非常多的流行的互联网协议,如:FTP, FTPS, HTTP, HTTPS, SCP, SFTP, TFTP, TELNET, DICT, LDAP, LDAPS and FILE等。curl支持SSL认证,HTTP POST/PUT,FTP上传,HTTP上传、代理、cookies、用户+密码认证、文件续传、代理管道等一系列强大功能。

curl是用C语言写的,但是绑定了很多开发语言。大体上可以把curl分成命令行工具和libcurl库两个部分,命令行工具可以直接输入指令完成相应功能,libcurl则是一个客户端URL传输库,是线程安全且兼容IPv6,可以非常方便地用来做相关开发。


How to Using Curl Lib:

Compile curl without openssl and zlib.

 
Step1:下载CURL 最近的几个版本,我是curl-7.21.5。然后解压到curl-7.21.5文件夹。


Step2:打开curl-7.21.5文件夹,找到vc6curl.dsw。就是VC6工程的文件。


Step3:用2008打开,选择 生成(B)-》生成解决方案(F7) ,不要点三角形那个启动调试


Step4:打开curl-7.21.5\lib\DLL-Debug 找到libcurld.dll和libcurld_imp.lib。


Step5:打开curl-7.21.5\include\找到curl文件和第四步找到的libcurld.dll和libcurld_imp.lib一起放到你新建的工程目录你。比如你新建了个名为:DDDDDD的工程,那么久把他们放到\Visual Studio 2008\Projects\DDDDDD\DDDDDD就是有很多.h 和。CPP的地方


Step6:在你工程MAIN函数前面 include"curl/curl.h" 不行的话就用include<curl/curl.h>


Step7:VS2008编代码的左边,在工程DDDDDD就是头文件上方右击属性-》配置属性-》链接器-》命令行有个附加选项那打入libcurld_imp.lib就OK了


  如果运行提示缺少libsasl.dll,就下个SVN,在安装目录下的bin目录下找到libsasl.dll,复制到工程目录下即可


  1. 静态和动态的libcurl库都有debug和release版本,分别位于cURL源代码lib子文件夹中的DLL-Debug、DLL-Release、LIB-Debug和LIB-Release文件夹
  2. curl的可执行文件也是按照相同的方式生成,分别使用对应的libcurl库。curl可执行文件分别位于cURL源代码src子文件夹中的DLL-Debug、DLL-Release、LIB-Debug和LIB-Release文件夹
  3. 代码生成的时候使用的是动态的CRT(C Runtime Library)


基于libcurl库的开发(Windows平台,MSVC2010开发环境)。
libcurl是一个简单易用的基于URL传输的客户端开发库,支持多种平台以及三十多种开发语言绑定。libcurl是线程安全的,兼容IPv6,功能强大且运行效率高。
在10环境中做libcurl开发,需要将静态库文件加到编译链接环境中,并且要dll动态运行库支持。

libcurl提供了一组C语言API函数直接调用。首先需要提到的两个函数就是curl_global_init()和curl_global_cleanup()。libcurl要用到一系列的全局常量,curl_global_init()函数就是初始化这些变量,并分配一些全局资源;curl_global_cleanup()则负责释放这些资源。因此一般情况下,在调用libcurl函数之前,先用curl_global_init(CURL_GLOBAL_ALL)做初始化,在调用完毕后,用curl_global_cleanup()
退出。需要注意的是,这些全局变量和资源并不是线程安全的,因此,在多线程应用的环境中,最好不要多次调用curl_global_init()和curl_global_cleanup(),调用其他函数并不会改变这些全局变量和资源。
libcurl支持3种不同的接口调用方式,分别是"easy"、"multi"和"share"模式。libcurl-easy是一组同步接口,函数都是curl_easy_*形式,这种模式调用curl_easy_perform()函数进行URL数据传输,直到传输完成函数才返回;libcurl-multi是一组异步接口,函数都是curl_multi_*形式,调用curl_multi_perform()函数进行传输,但是每次调用只传一片数据,我们可以用select()函数控制多个下载任务进行同步下载,来实现在一个线程中同时下载多个文件;libcurl-share允许在多线程中操作共享数据。下面以libcurl-easy为例讲一下libcurl的函数。

1、CURL *curl_easy_init()
此函数需要最先被调用,返回CRUL easy句柄;后续其他函数调用都要用到这个句柄。如果没有调用curl_global_init(),该函数自动调用,但是考虑到线程安全的问题,最好自己调用curl_global_init()。

2、CURLcode curl_easy_setopt(CURL *handle, CURLoption option, parameter)
所有参数和选项设置都是通过这个函数完成的,它告诉libcurl怎样去进行传输。参数handle即为curl_easy_init()返回的句柄,后面根据option的类型,设置相应的parameter值,该函数每次调用只能设置一个选项。具体的option讲解在这两篇博文中有较全面的介绍:
http://blog.163.com/wangsen_315/blog/static/9461414200882384555217/
http://blog.sina.com.cn/s/blog_4f9fc6e10100einf.html
这里只总结一下与下载有关的常用选项设置。

CURLOPT_URL
字符串类型,该选项设置要处理的URL地址,该选项是进行curl_easy_perform之前唯一必须要设置的选项。

CURLOPT_COOKIE
字符串类型,设置http头中的cookie信息。

CURLOPT_COOKIEFILE
字符串类型,同CURLOPT_COOKIE,不过cookie信息从文件中读取。

CURLOPT_FOLLOWLOCATION
布尔值类型,该参数设置为非零值表示follow服务器返回的重定向信息。

CURLOPT_POSTFIELDS
字符串类型,提交http的post操作字符串数据。

CURLOPT_TIMEOUT
long数值类型,设置函数执行的最长时间,时间单位为s。

CURLOPT_CONNECTTIMEOUT
long数值类型,设置连接服务器最长时间,时间单位为s;当置为0时表示无限长。

CURLOPT_MAX_RECV_SPEED_LARGE
curl_off_t类型数据,指定下载过程中最大速度,单位bytes/s。

CURLOPT_HEADERFUNCTION
函数指针类型,该选项设置一个处理接收到的header数据的回调函数,函数原型为:
size_t function( void *ptr, size_t size, size_t nmemb, void *stream);
其中,ptr指向接收到的header头数据,数据大小为size*nmemb,stream指向调用CURLOPT_WRITEHEADER选项设置的参数。该回调函数应返回实际处理的数据量大小,或者出错返回-1。

CURLOPT_WRITEFUNCTION
函数指针类型,该选项设置一个处理接收到的下载数据的回调函数,函数原型为:
size_t function( void *ptr, size_t size, size_t nmemb, void *stream);
其中,ptr指向接收到的数据,数据大小为size*nmemb,stream指向调用CURLOPT_WRITEDATA选项设置的参数。
如果函数指针置为NULL,则会调用默认的函数,将数据写入到由CURLOPT_WRITEDATA指定的FILE*中。

CURLOPT_HTTPHEADER
curl_slist结构体类型,该选项自定义请求头信息。

CURLOPT_NOPROGRESS
布尔值类型,设置该值为非零值关闭PHP为CRUL传输显示的进度条。

3、void curl_easy_reset(CURL *handle )
重新初始化CURL句柄的选项设置。

4、CURLcode curl_easy_getinfo(CURL *curl, CURLINFO info, ... )
查询CRUL会话的内部信息,具体说明请参考curl自带文档。

5、void curl_easy_cleanup(CURL * handle )
该函数与curl_easy_init函数成对出现,handle即为调用curl_easy_init返回的句柄。该函数在CURL会话结束退出时调用,之后handle无效。


The Basic Processes of Using Curl lib.

curl_easy_init()
curl_easy_setopt()
curl_easy_perform()
curl_easy_cleanup()

Upload File by Http Post

curl_global_init(CURL_GLOBAL_WIN32);  
CURL*easy_handle = curl_easy_init(); 
// 使用multi-parts form post 
curl_easy_setopt(easy_handle, CURLOPT_URL,http://localhost:8080/uploadServlet); 
curl_httppost*post = NULL; 
curl_httppost *last =NULL;  
// 文本数据 
curl_formadd(&post,&last, CURLFORM_COPYNAME, "filePath",CURLFORM_COPYCONTENTS, "tempfile", CURLFORM_END); 
 // 文本文件中的数据 
 curl_formadd(&post,&last, CURLFORM_COPYNAME, "file",CURLFORM_FILECONTENT, "ReadMe.txt", CURLFORM_END); 
 curl_easy_setopt(easy_handle, CURLOPT_HTTPPOST,post); 
 curl_easy_perform(easy_handle); 
 curl_formfree(post); 
 curl_easy_cleanup(easy_handle); 
 curl_global_cleanup(); 

Or

CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl)
{
    curl_formadd(&post, &last, 
        CURLFORM_COPYNAME, "file",
        CURLFORM_FILE, "C:\\rect.jpg",
        CURLFORM_END);
 
    curl_formadd(&post, &last, 
        CURLFORM_COPYNAME, "name",
        CURLFORM_COPYCONTENTS, "rect",
        CURLFORM_END);
 
    curl_easy_setopt(curl, CURLOPT_URL, "http://blah.com/upload.php");
    curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);
 
    res = curl_easy_perform(curl);
    if(res)
    {
        return 0;
    }
     
    curl_formfree(post);
}
else
{
    return 0;
}
 
curl_easy_cleanup(curl);

Upload File with Callback:

#include <stdio.h>
#include <string.h>
  
#include <curl/curl.h>
#include <curl/types.h> 
#include <curl/easy.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#ifdef WIN32
#include <io.h>
#else
#include <unistd.h>
#endif
  
/*
 * This example shows an FTP upload, with a rename of the file just after
 * a successful upload.
 *
 * Example based on source code provided by Erick Nuwendam. Thanks!
 */
  
#define LOCAL_FILE      "feed.txt"
#define RENAME_FILE_TO  "feed.zip"
  
/* NOTE: if you want this example to work on Windows with libcurl as a
   DLL, you MUST also provide a read callback with CURLOPT_READFUNCTION.
   Failing to do so will give you a crash since a DLL may not use the
   variable's memory when passed in to it from an app like this. */
static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *stream)
{
  /* 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 */
  size_t retcode = fread(ptr, size, nmemb, stream);
  
  printf("*** We read %d bytes from file\n", retcode);
  return retcode;
}
  
int main(void)
{
  CURL *curl;
  CURLcode res;
  FILE *hd_src;
  struct stat file_info;
  curl_off_t fsize;
   
  char *REMOTE_URL = "http://iss.netii.net/projects/message/";
  
  struct curl_slist *headerlist=NULL;
  static const char buf_2 [] = "RNTO " RENAME_FILE_TO;
  
  /* get the file size of the local file */
  if(stat(LOCAL_FILE, &file_info)) {
    printf("Couldnt open '%s': %s\n", LOCAL_FILE, strerror(errno));
    return 1;
  }
  fsize = (curl_off_t)file_info.st_size;
  
  printf("Local file size: %" CURL_FORMAT_CURL_OFF_T " bytes.\n", fsize);
  
  /* get a FILE * of the same file */
  hd_src = fopen(LOCAL_FILE, "rb");
  
  /* In windows, this will init the winsock stuff */
  curl_global_init(CURL_GLOBAL_ALL);
  
  /* get a curl handle */
  curl = curl_easy_init();
  if(curl) {
    /* build a list of commands to pass to libcurl */
    headerlist = curl_slist_append(headerlist, buf_2);
  
    /* we want to use our own read function */
    curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);
  
    /* enable uploading */
    curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
  
    /* specify target */
    curl_easy_setopt(curl,CURLOPT_URL, REMOTE_URL);
  
    /* pass in that last of FTP commands to run after the transfer */
    curl_easy_setopt(curl, CURLOPT_POSTQUOTE, headerlist);
  
    /* now specify which file to upload */
    curl_easy_setopt(curl, CURLOPT_READDATA, hd_src);
  
    /* Set the size of the file to upload (optional).  If you give a *_LARGE
       option you MUST make sure that the type of the passed-in argument is a
       curl_off_t. If you use CURLOPT_INFILESIZE (without _LARGE) you must
       make sure that to pass in a type 'long' argument. */
    curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE,
                     (curl_off_t)fsize);
  
    /* Now run off and do what you've been told! */
    res = curl_easy_perform(curl);
  
    /* clean up the FTP commands list */
    curl_slist_free_all (headerlist);
  
    /* always cleanup */
    curl_easy_cleanup(curl);
  }
  fclose(hd_src); /* close the local file */
  getchar();
  curl_global_cleanup();
  return 0;
}


Download File from Http

#define CURL_STATICLIB
#include <stdio.h>
#include <curl/curl.h>
#include <curl/types.h>
#include <curl/easy.h>
#include <string>

size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
    size_t written;
    written = fwrite(ptr, size, nmemb, stream);
    return written;
}

int main(void) {
    CURL *curl;
    FILE *fp;
    CURLcode res;
    char *url = "http://localhost/aaa.txt";
    char outfilename[FILENAME_MAX] = "C:\\bbb.txt";
    curl = curl_easy_init();
    if (curl) {
        fp = fopen(outfilename,"wb");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        fclose(fp);
    }
    return 0;
}



How to Using Curl Command Line:


curl的用法为:curl [options] [URL...] 

其中options是下载需要的参数,大约有80多个,curl的各个功能完全是依靠这些参数完成的。具体参数的使用,用户可以参考curl的man帮助。

-a/--append 上传文件时,附加到目标文件
 -A/--user-agent <string>  设置用户代理发送给服务器
 - anyauth   可以使用“任何”身份验证方法
 -b/--cookie <name=string/file> cookie字符串或文件读取位置
 - basic 使用HTTP基本验证
 -B/--use-ascii 使用ASCII /文本传输
 -c/--cookie-jar <file> 操作结束后把cookie写入到这个文件中
 -C/--continue-at <offset>  断点续转
 -d/--data <data>   HTTP POST方式传送数据
 --data-ascii <data>  以ascii的方式post数据
 --data-binary <data> 以二进制的方式post数据
 --negotiate     使用HTTP身份验证
 --digest        使用数字身份验证
 --disable-eprt  禁止使用EPRT或LPRT
 --disable-epsv  禁止使用EPSV
 -D/--dump-header <file> 把header信息写入到该文件中
 --egd-file <file> 为随机数据(SSL)设置EGD socket路径
 --tcp-nodelay   使用TCP_NODELAY选项
 -e/--referer 来源网址
 -E/--cert <cert[:passwd]> 客户端证书文件和密码 (SSL)
 --cert-type <type> 证书文件类型 (DER/PEM/ENG) (SSL)
 --key <key>     私钥文件名 (SSL)
 --key-type <type> 私钥文件类型 (DER/PEM/ENG) (SSL)
 --pass  <pass>  私钥密码 (SSL)
 --engine <eng>  加密引擎使用 (SSL). "--engine list" for list
 --cacert <file> CA证书 (SSL)
 --capath <directory> CA目录 (made using c_rehash) to verify peer against (SSL)
 --ciphers <list>  SSL密码
 --compressed    要求返回是压缩的形势 (using deflate or gzip)
 --connect-timeout <seconds> 设置最大请求时间
 --create-dirs   建立本地目录的目录层次结构
 --crlf          上传是把LF转变成CRLF
 -f/--fail          连接失败时不显示http错误
 --ftp-create-dirs 如果远程目录不存在,创建远程目录
 --ftp-method [multicwd/nocwd/singlecwd] 控制CWD的使用
 --ftp-pasv      使用 PASV/EPSV 代替端口
 --ftp-skip-pasv-ip 使用PASV的时候,忽略该IP地址
 --ftp-ssl       尝试用 SSL/TLS 来进行ftp数据传输
 --ftp-ssl-reqd  要求用 SSL/TLS 来进行ftp数据传输
 -F/--form <name=content> 模拟http表单提交数据
 -form-string <name=string> 模拟http表单提交数据
 -g/--globoff 禁用网址序列和范围使用{}和[]
 -G/--get 以get的方式来发送数据
 -h/--help 帮助
 -H/--header <line>自定义头信息传递给服务器
 --ignore-content-length  忽略的HTTP头信息的长度
 -i/--include 输出时包括protocol头信息
 -I/--head  只显示文档信息
 从文件中读取-j/--junk-session-cookies忽略会话Cookie
 - 界面<interface>指定网络接口/地址使用
 - krb4 <级别>启用与指定的安全级别krb4
 -j/--junk-session-cookies 读取文件进忽略session cookie
 --interface <interface> 使用指定网络接口/地址
 --krb4 <level>  使用指定安全级别的krb4
 -k/--insecure 允许不使用证书到SSL站点
 -K/--config  指定的配置文件读取
 -l/--list-only 列出ftp目录下的文件名称
 --limit-rate <rate> 设置传输速度
 --local-port<NUM> 强制使用本地端口号
 -m/--max-time <seconds> 设置最大传输时间
 --max-redirs <num> 设置最大读取的目录数
 --max-filesize <bytes> 设置最大下载的文件总量
 -M/--manual  显示全手动
 -n/--netrc 从netrc文件中读取用户名和密码
 --netrc-optional 使用 .netrc 或者 URL来覆盖-n
 --ntlm          使用 HTTP NTLM 身份验证
 -N/--no-buffer 禁用缓冲输出
 -o/--output 把输出写到该文件中
 -O/--remote-name 把输出写到该文件中,保留远程文件的文件名
 -p/--proxytunnel   使用HTTP代理
 --proxy-anyauth 选择任一代理身份验证方法
 --proxy-basic   在代理上使用基本身份验证
 --proxy-digest  在代理上使用数字身份验证
 --proxy-ntlm    在代理上使用ntlm身份验证
 -P/--ftp-port <address> 使用端口地址,而不是使用PASV
 -Q/--quote <cmd>文件传输前,发送命令到服务器
 -r/--range <range>检索来自HTTP/1.1或FTP服务器字节范围
 --range-file 读取(SSL)的随机文件
 -R/--remote-time   在本地生成文件时,保留远程文件时间
 --retry <num>   传输出现问题时,重试的次数
 --retry-delay <seconds>  传输出现问题时,设置重试间隔时间
 --retry-max-time <seconds> 传输出现问题时,设置最大重试时间
 -s/--silent静音模式。不输出任何东西
 -S/--show-error   显示错误
 --socks4 <host[:port]> 用socks4代理给定主机和端口
 --socks5 <host[:port]> 用socks5代理给定主机和端口
 --stderr <file>
 -t/--telnet-option <OPT=val> Telnet选项设置
 --trace <file>  对指定文件进行debug
 --trace-ascii <file> Like --跟踪但没有hex输出
 --trace-time    跟踪/详细输出时,添加时间戳
 -T/--upload-file <file> 上传文件
 --url <URL>     Spet URL to work with
 -u/--user <user[:password]>设置服务器的用户和密码
 -U/--proxy-user <user[:password]>设置代理用户名和密码
 -v/--verbose
 -V/--version 显示版本信息
 -w/--write-out [format]什么输出完成后
 -x/--proxy <host[:port]>在给定的端口上使用HTTP代理
 -X/--request <command>指定什么命令
 -y/--speed-time 放弃限速所要的时间。默认为30
 -Y/--speed-limit 停止传输速度的限制,速度时间'秒
 -z/--time-cond  传送时间设置
 -0/--http1.0  使用HTTP 1.0
 -1/--tlsv1  使用TLSv1(SSL)
 -2/--sslv2 使用SSLv2的(SSL)
 -3/--sslv3         使用的SSLv3(SSL)
 --3p-quote      like -Q for the source URL for 3rd party transfer
 --3p-url        使用url,进行第三方传送
 --3p-user       使用用户名和密码,进行第三方传送
 -4/--ipv4   使用IP4
 -6/--ipv6   使用IP6
 -#/--progress-bar 用进度条显示当前的传送状态




Summary:

curl非常博大,要想用好这个工具,除了详细学习参数之外,还需要深刻理解http的各种协议与URL的各个语法。推荐读物:

RFC 2616 HTTP协议语法的定义。
RFC 2396 URL语法的定义。
RFC 2109 Cookie是怎样工作的。
RFC 1867 HTTP如何POST,以及POST的格式。


原文地址:https://www.cnblogs.com/yefengmeander/p/2887541.html