libcurl学习

libcurl是C语言开发的网络库,支持多种网络协议。

libcurl是一个跨平台的开源网络协议库,支持http,https,rstp等多种协议。ibcurl同样支持HTTPS证书授权,HTTP POST,HTTP PUT,FTP上传,HTTP基本表单上传,代理,cookies,用户认证。

Curl提供了一系列接口,可分为easy interface和multinterface,前者是阻塞的,后者可用于多线程,可做非阻塞应用。两者不是独立的,multi interface也依赖于easy interface。

Easy interface

初始化/清理curl环境
curl_global_init/curl_global_cleanup

初始化/释放easy handle
curl_easy_init/curl_easy_cleanup

设url
curl_easy_setop(easy_handle_,CURLOPT_URL,"http://www.xxx.com/RL.do");


设HTTP方法
POST
curl_easy_setopt(easy_handle_,CURLOPT_POST,1);

GET
curl_easy_setop(easy_handle_,CURLOPT_HTTPGET,1);

PUT
curl_easy_setopt(easy_handele_,CURLOPT_UPLOAD,1);

POST multipart/formdata类型
curl_easy_setopt(easy_handle_,CURLOPT_HTTPOST,formpost);

设body
curl_easy_setopt(easy_handle_,CURLOPT_poSTFIELDS,body.c_str());

设置超时时间,10s内数据接收未完成则直接退出
curl_easy_setop(easy_handle_,CURLOPT_TIMEOUT, 10);

设置User-Agent
curl_easy_setopt(easy_handele_,CURLOPT_USERAGENT,"XXX");

接收数据,输入类的静态函数地址
curl_easy_setopt(easy_handle_,CURLOPT_WRITEFUNCTION,&RecvDAta);
curl_easy_setopt(easy_handle_,CURLOPT_WRITEDATA,this);

执行
curl_easy_perform(easy_handle_);

取得redirect url
curl_easy_getinfo(easy_handle_,CURLINFO_REDIRECT_URL,&redirect_url);

取得cookies,若要取得某一cookie值,需解析
curl_easy_getinfo(easy_handle_,CURLINFO_COOKIELIST, &cookies)

取得response code
curl_easy_getinfo(easy_handle_,CURLINFO_RESPONSE_CODE, &res_code_);

cookie操作

设置客户端接收到的cookie的存放目录

curl_easy_setopt(easy_handle_, CURLOPT_COOKIEJAR, cookie_file_.c_str());

设置读取的cookie文件

curl_easy_setopt(easy_handle_, CURLOPT_COOKIEFILE, cookie_file_.c_str());



上传文件

方法一:传入文件路径,不需要写读文件内容的代码

curl_formadd(&formpost, &lastptr,
    CURLFORM_COPYNAME, "photos",
    CURLFORM_FILE, utf8_file_name.c_str(), // 文件路径
    CURLFORM_END);

方法二:先将文件内容读入内存,将内容传入

curl_formadd(&formpost, &lastptr,
               CURLFORM_COPYNAME, "photos",
               CURLFORM_BUFFER, "a.jpg",
               CURLFORM_BUF
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值