Curl学习

libcurl有两个接口

easy接口 同步、高效 前缀curl_easy。

multi接口 异步  前缀curl_multi。multi使用单线程

 

easy使用范例

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <curl/curl.h>

//回调

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

int main(void)
{
  CURL *curl_handle;
  static const char *headerfilename = "head.out";
  FILE *headerfile;
  static const char *bodyfilename = "body.out";
  FILE *bodyfile;

  curl_global_init(CURL_GLOBAL_ALL);

  /* init the curl session */
  curl_handle = curl_easy_init();

  /* set URL to get */
  curl_easy_setopt(curl_handle, CURLOPT_URL, "http://example.com");

  /* no progress meter please */
  curl_easy_setopt(curl_handle, CURLOPT_NOPROGRESS, 1L);

  /* send all data to this function  */
  curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, write_data);

  /* open the files */
  headerfile = fopen(headerfilename,"wb");
  if (headerfile == NULL) {
    curl_easy_cleanup(curl_handle);
    return -1;
  }
  bodyfile = fopen(bodyfilename,"wb");
  if (bodyfile == NULL) {
    curl_easy_cleanup(curl_handle);
    return -1;
  }

  /* we want the headers be written to this file handle */
  curl_easy_setopt(curl_handle,   CURLOPT_WRITEHEADER, headerfile);

  /* we want the body be written to this file handle instead of stdout */
  curl_easy_setopt(curl_handle,   CURLOPT_WRITEDATA, bodyfile);

  /* get it! */
  curl_easy_perform(curl_handle);

  /* close the header file */
  fclose(headerfile);

  /* close the body file */
  fclose(bodyfile);

  /* cleanup curl stuff */
  curl_easy_cleanup(curl_handle);

  return 0;
}

 

multi使用范例

#include <stdio.h>
#include <string.h>
#include <sys/time.h>

#include <curl/curl.h>

int main(void)
{
  CURL *curl;

  CURLM *multi_handle;
  int still_running;

  struct curl_httppost *formpost=NULL;
  struct curl_httppost *lastptr=NULL;
  struct curl_slist *headerlist=NULL;
  static const char buf[] = "Expect:";

  /* Fill in the file upload field. This makes libcurl load data from
     the given file name when curl_easy_perform() is called. */
  curl_formadd(&formpost,
               &lastptr,
               CURLFORM_COPYNAME, "sendfile",
               CURLFORM_FILE, "postit2.c",
               CURLFORM_END);

  /* Fill in the filename field */
  curl_formadd(&formpost,
               &lastptr,
               CURLFORM_COPYNAME, "filename",
               CURLFORM_COPYCONTENTS, "postit2.c",
               CURLFORM_END);

  /* Fill in the submit field too, even if this is rarely needed */
  curl_formadd(&formpost,
               &lastptr,
               CURLFORM_COPYNAME, "submit",
               CURLFORM_COPYCONTENTS, "send",
               CURLFORM_END);

  curl = curl_easy_init();
  multi_handle = curl_multi_init();

  /* initalize custom header list (stating that Expect: 100-continue is not
     wanted */
  headerlist = curl_slist_append(headerlist, buf);
  if(curl && multi_handle) {

    /* what URL that receives this POST */
    curl_easy_setopt(curl, CURLOPT_URL, "http://www.example.com/upload.cgi");
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);

    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);
    curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);

    curl_multi_add_handle(multi_handle, curl);

    curl_multi_perform(multi_handle, &still_running);

    do {
      struct timeval timeout;
      int rc; /* select() return code */

      fd_set fdread;
      fd_set fdwrite;
      fd_set fdexcep;
      int maxfd = -1;

      long curl_timeo = -1;

      FD_ZERO(&fdread);
      FD_ZERO(&fdwrite);
      FD_ZERO(&fdexcep);

      /* set a suitable timeout to play around with */
      timeout.tv_sec = 1;
      timeout.tv_usec = 0;

      curl_multi_timeout(multi_handle, &curl_timeo);
      if(curl_timeo >= 0) {
        timeout.tv_sec = curl_timeo / 1000;
        if(timeout.tv_sec > 1)
          timeout.tv_sec = 1;
        else
          timeout.tv_usec = (curl_timeo % 1000) * 1000;
      }

      /* get file descriptors from the transfers */
      curl_multi_fdset(multi_handle, &fdread, &fdwrite, &fdexcep, &maxfd);

      /* In a real-world program you OF COURSE check the return code of the
         function calls.  On success, the value of maxfd is guaranteed to be
         greater or equal than -1.  We call select(maxfd + 1, ...), specially in
         case of (maxfd == -1), we call select(0, ...), which is basically equal
         to sleep. */

      rc = select(maxfd+1, &fdread, &fdwrite, &fdexcep, &timeout);

      switch(rc) {
      case -1:
        /* select error */
        break;
      case 0:
      default:
        /* timeout or readable/writable sockets */
        printf("perform!\n");
        curl_multi_perform(multi_handle, &still_running);
        printf("running: %d!\n", still_running);
        break;
      }
    } while(still_running);

    curl_multi_cleanup(multi_handle);

    /* always cleanup */
    curl_easy_cleanup(curl);

    /* then cleanup the formpost chain */
    curl_formfree(formpost);

    /* free slist */
    curl_slist_free_all (headerlist);
  }
  return 0;
}

Curl学习

时间: 2024-12-28 21:51:58

Curl学习的相关文章

[转帖]可能是东半球最好的 Curl 学习指南,强烈建议收藏!

可能是东半球最好的 Curl 学习指南,强烈建议收藏! http://www.itpub.net/2019/09/30/3302/ 记得转帖过.. 简介 curl 是常用的命令行工具,用来请求 Web 服务器.它的名字就是客户端(client)的 URL 工具的意思. 它的功能非常强大,命令行参数多达几十种.如果熟练的话,完全可以取代 Postman 这一类的图形界面工具. 使用实例 本文介绍它的主要命令行参数,作为日常的参考,方便查阅.内容主要翻译自 <curl cookbook>.为了节约

cURL 学习笔记与总结(2)网页爬虫、天气预报

例1.一个简单的 curl 获取百度 html 的爬虫程序(crawler): spider.php <?php /* 获取百度html的简单网页爬虫 */ $curl = curl_init('http://www.baidu.com'); //resource(2, curl) curl_exec($curl); curl_close($curl); 访问该页面: 例2.下载一个网页(百度)并把内容中的百度替换成'PHP'之后输出 <?php /* 下载一个网页(百度)并把内容中的百度替换

cURL 学习笔记与总结(1)概念

概念: cURL(Client URL Library Functions)is a command line tool for transfering data with URL syntax(使用 URL 语法传输数据的命令行工具),即客户端向服务器请求资源的工具. 使用场景: ① 网页资源(例如编写网页爬虫) ② WebService 数据接口资源(比如动态获取接口数据,比如天气.号码归属地等) ③ FTP 服务器里的文件资源(下载 FTP 服务器里面的文件) ④ 其他资源(所有网络上的资

curl 学习

<?php // $username =13800138000; // $password =123456; // $sendto =13912345678; // $message = "测试一个试试看!"; // $curlPost = 'username='.urlencode($username).'&password='.urlencode($password).'&sendto='.urlencode($sendto).'&message='.

curl 学习保存

原文地址 http://www.jb51.net/article/48866.htm php中的curl使用入门教程和常见用法实例 作者: 字体:[增加 减小] 类型:转载 起先cURL是做为一种命令行工具设计出来的,比较幸运的是,php也支持cURL了.通过cURL这个利器,我们能在php程序中自由地发送HTTP请求到某个url来获取或者提交数据,并且支持其它多种协议,比如FTP,Telnet以及SMTP等.在这篇博文中,我将简述下,在php中具体怎么使用cURL来处理一些事情. 一.curl

curl学习总结

1.接口    function interface($postfields=array(),$url){        //设置post请求HTTP头字段的数组        $httpheader=array("content-type: application/x-www-form-urlencoded;charset=UTF-8");                //初始化curl        $ch=curl_init();                /**     

cURL 学习笔记与总结(3)模拟登录博客园并下载个人随笔首页

代码: login.php <?php $data = 'tbUserName=huangdi0912&tbPassword=******&chkRemember=1'; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, 'http://passport.cnblogs.com/login.aspx?ReturnUrl=http%3A%2F%2Fwww.cnblogs.com%2F');//登录页面 curl_setopt($c

cURL 学习笔记与总结(4)使用 curl 从 ftp 上下载文件与上传文件到 ftp

下载: <?php $curlobj = curl_init(); curl_setopt($curlobj, CURLOPT_URL, "ftp://192.***.*.***/文件名"); curl_setopt($curlobj, CURLOPT_HEADER, 0); curl_setopt($curlobj, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curlobj, CURLOPT_TIMEOUT, 300); // times

curl学习之curl_setopt参数设置大总结

CURL函数库里最重要的函数是curl_setopt(),它可以通过设定CURL函数库定义的选项来定制HTTP请求 使用方法:bool curl_setopt (int ch, string option, mixed value) curl_setopt()函数将为一个CURL会话设置选项.option参数是你想要的设置,value是这个选项给定的值. 下列选项的值将被作为长整形使用(在option参数中指定): CURLOPT_INFILESIZE: //当你上传一个文件到远程站点,这个选项