libcurl的使用总结(二)
本篇主要是一些使用示例,由于部分代码是来源网上,原作者已经无法考证,所以如有原作者看到,可以告诉我,我给注明~
另:文末附有所有代码的打包下载,均在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)
附:代码程序打包下载
建议继续学习:
- iPhone下的libcurl with SSL for iOS (阅读:5022)
- libcurl中使用curl_easy_getinfo 产生段错误分析 (阅读:4160)
- libcurl的使用总结(一) (阅读:3294)
- 关于libcurl不发包的bug定位 (阅读:3069)
扫一扫订阅我的微信号:IT技术博客大学习
- 作者:Dante 来源: Vimer
- 标签: libcurl
- 发布时间:2010-03-29 09:06:12
- [55] IOS安全–浅谈关于IOS加固的几种方法
- [54] android 开发入门
- [54] 如何拿下简短的域名
- [54] 图书馆的世界纪录
- [52] Go Reflect 性能
- [52] Oracle MTS模式下 进程地址与会话信
- [49] 【社会化设计】自我(self)部分――欢迎区
- [48] 读书笔记-壹百度:百度十年千倍的29条法则
- [41] 程序员技术练级攻略
- [35] 视觉调整-设计师 vs. 逻辑