libcurl库的使用
来源:互联网 发布:mad制作软件 编辑:程序博客网 时间:2024/05/16 18:32
libcurl库的使用
libcurl是一个跨平台的网络协议库,支持http, https, ftp, gopher, telnet, dict, file, 和ldap 协议。libcurl同样支持HTTPS证书授权,HTTP POST, HTTP PUT, FTP 上传, HTTP基本表单上传,代理,cookies,和用户认证。
在基于LibCurl的程序里,主要采用callback function(回调函数)的形式完成传输任务,用户在传输前设置好各类参数和回调函数,当满足条件时libcurl将调用用户的回调函数实现特定功能。
完成传输任务的流程:
- 调用curl_global_init()初始化libcurl
- 调用curl_easy_init()函数得到easy interface型指针
- 调用curl_easy_setopt()设置传输选项
- 根据curl_easy_setopt()设置的传输选项,实现回调函数以完成用户特定任务
- 调用curl_easy_perform函数完成传输任务
- 调用curl_easy_cleanup释放内存
在整个过程中设置curl_easy_setopt参数是最关键的,几乎所有的libcurl程序都要使用它。
基本函数
- CURLcode curl_global_init(long flags)
该函数只能使用一次。(在调用curl_global_cleanup函数后可再用),libcurl是线程安全的,但curl_global_init不能保证线程安全,所以应该将该函数调用放在主线程中。
void curl_global_cleanup
在结束libcurl使用的时候,用来对curl_global_init做的工作清理,类似于close的函数。同样的应该在主函数中调用该函数。
CURL* curl_easy_init()
用来初始化一个CURL的指针,相应的在调用结束时要用curl_easy_cleanup函数清理。
- void curl_easy_cleanup(CURL* handle)
用来结束一个会话,与curl_easy_init配合着用。
- CURLcode curl_easy_setopt(CURL* handle, CURLoption option, parameter)
告诉curl库,程序将有如何的行为。
1 CURL类型的指针
2 各种CURLoption类型的选项
3 parameter 既可以是个函数的指针,也可以是某个对象的指针,也可以是个long型的变量。
- CURLcode curl_easy_perform(CURL* handle)
在初始化CURL类型的指针以及curl_easy_setopt完成后调用,让设置而的option运作起来。
curl_easy_setopt函数部分说明
- CURLOPT_URL
设置访问URL
- CURLOPT_WRITEFUNCTION, CURLOPT_WRITEDATA
回调函数原型为:size_t function(void* ptr, size_t size, size_t nmemb, void* stream); 函数将在libcurl接收到数据后调用,因此函数多做数据保存的功能,如处理下载文件。CURLOPT_WRITEDATA用于表明CURLOPT_WRITEFUNCTION中的steam指针的来源。
- 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指针的来源。
- CURLOPT_READFUNCTION, CURLOPT_READDATA
libcurl需要读取数据传递给远程主机时将调用CURLOPT_READFUNCTION指定的函数,函数原型是:size_t function(void* ptr, size_t size, size_t nmemb, void* stream). CURLOPT_READDATA表明CURLOPT_READFUNCTION函数原型中的steam指针来源。
- CURLOPT_NOPROGRESS, CURLOPT_PROGRESSFUNCTION, CURLOPT_PROGRESSDATA
跟数据传输进度相关的参数。CURLOPT_PROGRESSFUNCTION指定的函数正常情况下每秒被libcurl调用一次,为了使CURLOPT_PROGRESSFUNCTION被调用,CURLOPT_NOPROGRESS必须被设置为false, CURLOPT_PROGRESSDATA指定的参数将作为CURLOPT_PROGRESSFUNCTION指定函数的第一个参数。
- CURLOPT_TIMEOUT, CURLOPT_CONNECTIONTIMEOUT
设置传输时间,设置连接等待时间。
- 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,指定希望开始传递的偏移量。
curl_easy_perform函数说明(返回值)
- CURLE_OK
任务完成一切都好
- CURLE_UNSUPPORTED_PROTOCOL
不支持的协议,由URL的头部指定
- CURLE_REMOTE_ACCESS_DENIED
访问被拒绝
- CURLE_HTTP_RETURNED_ERROR
http返回错误
- CURLE_READ_ERROR
读取本地文件错误
libcurl使用HTTP消息头
当使用libcurl发送http请求时,它会自动添加一些http头。可以通过CURLOPT_HTTPHEADER属性手动替换、添加或删除相应的HTTP消息头。
Host
http1.1版本都要求客户端请求提供这个消息头。
Pragma
“no-cache”。表示不要缓冲数据。
Accept
“*/*”。表示允许接收任何类型的数据
Expect
以POST的方式向HTTP服务器提交请求时,libcurl会设置该消息头为“100-continue”,它要求服务器正式处理该请求之前,返回一个“OK”消息。
代码实例
- 基本的http GET/POST操作
#include <stdio.h>#include <curl/curl.h>bool getUrl(char *filename){ CURL *curl; CURLcode res; FILE *fp; if ((fp = fopen(filename, "w")) == NULL) // 返回结果用文件存储 return false; struct curl_slist *headers = NULL; headers = curl_slist_append(headers, "Accept: Agent-007"); curl = curl_easy_init(); // 初始化 if (curl) { //curl_easy_setopt(curl, CURLOPT_PROXY, "10.99.60.201:8080");// 代理 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);// 改协议头 curl_easy_setopt(curl, CURLOPT_URL,"http://www.baidu.com"); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); //将返回的http头输出到fp指向的文件 curl_easy_setopt(curl, CURLOPT_HEADERDATA, fp); //将返回的html主体数据输出到fp指向的文件 res = curl_easy_perform(curl); // 执行 if (res != 0) { curl_slist_free_all(headers); curl_easy_cleanup(curl); } fclose(fp); return true; }}bool postUrl(char *filename){ CURL *curl; CURLcode res; FILE *fp; if ((fp = fopen(filename, "w")) == NULL) return false; curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "/tmp/cookie.txt"); // 指定cookie文件 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "&logintype=uid&u=xieyan&psw=xxx86"); // 指定post内容 //curl_easy_setopt(curl, CURLOPT_PROXY, "10.99.60.201:8080"); curl_easy_setopt(curl, CURLOPT_URL, " http://mail.sina.com.cn/cgi-bin/login.cgi "); // 指定url curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); res = curl_easy_perform(curl); curl_easy_cleanup(curl); } fclose(fp); return true;}int main(void){ getUrl("/tmp/get.html"); postUrl("/tmp/post.html");}
- 获取html网页
#include <stdio.h>#include <curl/curl.h>#include <stdlib.h>int main(int argc, char *argv[]){ CURL *curl; //定义CURL类型的指针CURLcode res; //定义CURLcode类型的变量,保存返回状态码 if(argc!=2) { printf("Usage : file <url>;\n"); exit(1); } curl = curl_easy_init(); //初始化一个CURL类型的指针 if(curl!=NULL) { //设置curl选项. 其中CURLOPT_URL是让用户指 定url. argv[1]中存放的命令行传进来的网址 curl_easy_setopt(curl, CURLOPT_URL, argv[1]); //调用curl_easy_perform 执行我们的设置.并进行相关的操作. 在这 里只在屏幕上显示出来. res = curl_easy_perform(curl); //清除curl操作. curl_easy_cleanup(curl); } return 0;}
- 网页下载保存实例
// 采用CURLOPT_WRITEFUNCTION 实现网页下载保存功能#include <stdio.h>;#include <stdlib.h>;#include <unistd.h>;#include <curl/curl.h>;#include <curl/types.h>;#include <curl/easy.h>;FILE *fp; //定义FILE类型指针//这个函数是为了符合CURLOPT_WRITEFUNCTION而构造的//完成数据保存功能size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream) { int written = fwrite(ptr, size, nmemb, (FILE *)fp); return written;}int main(int argc, char *argv[]){ CURL *curl; curl_global_init(CURL_GLOBAL_ALL); curl=curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, argv[1]); if((fp=fopen(argv[2],"w"))==NULL) { curl_easy_cleanup(curl); exit(1); }////CURLOPT_WRITEFUNCTION 将后继的动作交给write_data函数处理 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); curl_easy_perform(curl); curl_easy_cleanup(curl); exit(0);}
- 进度条实例显示文件下载进度
// 采用CURLOPT_NOPROGRESS, CURLOPT_PROGRESSFUNCTION CURLOPT_PROGRESSDATA 实现文件传输进度提示功能//函数采用了gtk库,故编译时需指定gtk库//函数启动专门的线程用于显示gtk 进度条bar#include <stdio.h>#include <gtk/gtk.h>#include <curl/curl.h>#include <curl/types.h> /* new for v7 */#include <curl/easy.h> /* new for v7 */GtkWidget *Bar;////这个函数是为了符合CURLOPT_WRITEFUNCTION而构造的//完成数据保存功能size_t my_write_func(void *ptr, size_t size, size_t nmemb, FILE *stream){ return fwrite(ptr, size, nmemb, stream);}//这个函数是为了符合CURLOPT_READFUNCTION而构造的//数据上传时使用size_t my_read_func(void *ptr, size_t size, size_t nmemb, FILE *stream){ return fread(ptr, size, nmemb, stream);}//这个函数是为了符合CURLOPT_PROGRESSFUNCTION而构造的//显示文件传输进度,t代表文件大小,d代表传 输已经完成部分int my_progress_func(GtkWidget *bar, double t, /* dltotal */ double d, /* dlnow */ double ultotal, double ulnow){/* printf("%d / %d (%g %%)\n", d, t, d*100.0/t);*/ gdk_threads_enter(); gtk_progress_set_value(GTK_PROGRESS(bar), d*100.0/t); gdk_threads_leave(); return 0;}void *my_thread(void *ptr){ CURL *curl; CURLcode res; FILE *outfile; gchar *url = ptr; curl = curl_easy_init(); if(curl) { outfile = fopen("test.curl", "w"); curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_WRITEDATA, outfile); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_write_func); curl_easy_setopt(curl, CURLOPT_READFUNCTION, my_read_func); curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L); curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, my_progress_func); curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, Bar); res = curl_easy_perform(curl); fclose(outfile); /* always cleanup */ curl_easy_cleanup(curl); } return NULL;}int main(int argc, char **argv){ GtkWidget *Window, *Frame, *Frame2; GtkAdjustment *adj; /* Must initialize libcurl before any threads are started */ curl_global_init(CURL_GLOBAL_ALL); /* Init thread */ g_thread_init(NULL); gtk_init(&argc, &argv); Window = gtk_window_new(GTK_WINDOW_TOPLEVEL); Frame = gtk_frame_new(NULL); gtk_frame_set_shadow_type(GTK_FRAME(Frame), GTK_SHADOW_OUT); gtk_container_add(GTK_CONTAINER(Window), Frame); Frame2 = gtk_frame_new(NULL); gtk_frame_set_shadow_type(GTK_FRAME(Frame2), GTK_SHADOW_IN); gtk_container_add(GTK_CONTAINER(Frame), Frame2); gtk_container_set_border_width(GTK_CONTAINER(Frame2), 5); adj = (GtkAdjustment*)gtk_adjustment_new(0, 0, 100, 0, 0, 0); Bar = gtk_progress_bar_new_with_adjustment(adj); gtk_container_add(GTK_CONTAINER(Frame2), Bar); gtk_widget_show_all(Window); if (!g_thread_create(&my_thread, argv[1], FALSE, NULL) != 0) g_warning("can't create the thread"); gdk_threads_enter(); gtk_main(); gdk_threads_leave(); return 0;}
- 断点续传实例
//采用CURLOPT_RESUME_FROM_LARGE 实现文件断点续传功能#include <stdlib.h>#include <stdio.h>#include <sys/stat.h>#include <curl/curl.h>//这个函数为CURLOPT_HEADERFUNCTION参数构造/* 从http头部获取文件size*/size_t getcontentlengthfunc(void *ptr, size_t size, size_t nmemb, void *stream) { int r; long len = 0; /* _snscanf() is Win32 specific */ // r = _snscanf(ptr, size * nmemb, "Content-Length: %ld\n", &len); r = sscanf(ptr, "Content-Length: %ld\n", &len); if (r) /* Microsoft: we don't read the specs */ *((long *) stream) = len; return size * nmemb;}/* 保存下载文件 */size_t wirtefunc(void *ptr, size_t size, size_t nmemb, void *stream){ return fwrite(ptr, size, nmemb, stream);}/*读取上传文件 */size_t readfunc(void *ptr, size_t size, size_t nmemb, void *stream){ FILE *f = stream; size_t n; if (ferror(f)) return CURL_READFUNC_ABORT; n = fread(ptr, size, nmemb, f) * size; return n;}// 下载 或者上传文件函数int download(CURL *curlhandle, const char * remotepath, const char * localpath, long timeout, long tries){ FILE *f; curl_off_t local_file_len = -1 ; long filesize =0 ; CURLcode r = CURLE_GOT_NOTHING; int c; struct stat file_info; int use_resume = 0; /* 得到本地文件大小 */ //if(access(localpath,F_OK) ==0) if(stat(localpath, &file_info) == 0) { local_file_len = file_info.st_size; use_resume = 1; } //采用追加方式打开文件,便于实现文件断点续传工作 f = fopen(localpath, "ab+"); if (f == NULL) { perror(NULL); return 0; } //curl_easy_setopt(curlhandle, CURLOPT_UPLOAD, 1L); curl_easy_setopt(curlhandle, CURLOPT_URL, remotepath); curl_easy_setopt(curlhandle, CURLOPT_CONNECTTIMEOUT, timeout); // 设置连接超时,单位秒 //设置http 头部处理函数 curl_easy_setopt(curlhandle, CURLOPT_HEADERFUNCTION, getcontentlengthfunc); curl_easy_setopt(curlhandle, CURLOPT_HEADERDATA, &filesize); // 设置文件续传的位置给libcurl curl_easy_setopt(curlhandle, CURLOPT_RESUME_FROM_LARGE, use_resume?local_file_len:0); curl_easy_setopt(curlhandle, CURLOPT_WRITEDATA, f); curl_easy_setopt(curlhandle, CURLOPT_WRITEFUNCTION, wirtefunc); //curl_easy_setopt(curlhandle, CURLOPT_READFUNCTION, readfunc); //curl_easy_setopt(curlhandle, CURLOPT_READDATA, f); curl_easy_setopt(curlhandle, CURLOPT_NOPROGRESS, 1L); curl_easy_setopt(curlhandle, CURLOPT_VERBOSE, 1L); r = curl_easy_perform(curlhandle); fclose(f); if (r == CURLE_OK) return 1; else { fprintf(stderr, "%s\n", curl_easy_strerror(r)); return 0; }}int main(int c, char **argv) { CURL *curlhandle = NULL; curl_global_init(CURL_GLOBAL_ALL); curlhandle = curl_easy_init(); //download(curlhandle, "ftp://user:pass@host/path/file", "C:\\file", 0, 3); download(curlhandle , "http://software.sky-union.cn/index.asp","/work/index.asp",1,3); curl_easy_cleanup(curlhandle); curl_global_cleanup(); return 0;}
- libcurl库的使用
- libcurl库的使用
- libcurl库的使用
- libcurl库的使用
- libcurl库的使用
- libcurl库的使用
- libcurl库的使用(通过libcurl库下载url图像)
- libcurl库的使用的一些心得
- 使用libcurl库进行HTTP的下载
- iOS开发之libcurl库的使用
- 关于libcurl库使用的一些问题
- linux 下 libcurl 库的使用
- libcurl的使用
- libcurl的使用
- libcurl的使用总结
- libcurl的使用
- libcurl的使用总结
- libcurl的简单使用
- idea快捷键
- 区分event对象中的[clientX,offsetX,screenX,pageX]
- RTSP客户端接收存储数据(live555库中的openRTSP实例)
- Web安全漏洞类型
- 构建ZooKeeper应用(4)
- libcurl库的使用
- android:layout_gravity="right"控制LinearLayout中控件居右显示失败
- ZooKeeper管理分布式环境中的数据(5)
- HDOJ 1335 Basically Speaking
- gcc attribute属性和section选项
- spring-aop通知
- [live555]rtsp直播基于live555的实现
- 机器学习的框架(一个框架解决几乎所有机器学习的问题)
- 使用jquery设置图片只可点击一次