LibCURL 简易使用

本文基于Code::Block + Mingw ,参考http://blog.163.com/xu_chao2000/blog/static/27770610200801303252802/

1) 从http://curl.haxx.se/download.html 下载源代码,解压

  1. 打开命令行,执行Mingw目录下的mingwvars.bat。

3)进入curl的lib目录,执行以下命令:mingw32-make -f Makefile.m32 ,会生成libcurl.dll 以及 libcurldll.a,(默认是动态库配置)

  1. COPY相应文件到CodeBlock建立的应用程序目录

5)代码如下:

主要代码块

   1: int main()
   2: {
   3:     CURL *curl_handle=NULL;
   4:     CURLcode code;
   5:     string buffer;
   6:     //原始的是CURL_GLOBAL_ALL ,还没研究出区别
   7:     curl_global_init(CURL_GLOBAL_DEFAULT);
   8:     char* url="www.google.com";
   9:      if (!init(curl_handle,url,&buffer ))
  10:      {
  11:         fprintf(stderr, "Connection initializion failedn");
  12:         exit(EXIT_FAILURE);
  13:      }
  14:      code = curl_easy_perform(curl_handle);
  15:      if (code != CURLE_OK)
  16:      {
  17:         fprintf(stderr, "Failed to get '%s' [%s]n", url, errorBuffer);
  18:         exit(EXIT_FAILURE);
  19:      }
  20:      curl_easy_cleanup(curl_handle);
  21:      printf("%sn",buffer.c_str());
  22: }
  23:
  24: static bool init(CURL *&conn, char *url,string *p_buffer)
  25: {
  26:     CURLcode code;
  27:     conn = curl_easy_init();
  28:     if (conn == NULL)
  29:     {
  30:         fprintf(stderr, "Failed to create CURL connectionn");
  31:         exit(EXIT_FAILURE);
  32:     }
  33:     code = curl_easy_setopt(conn, CURLOPT_ERRORBUFFER, errorBuffer);
  34:     if (code != CURLE_OK)
  35:     {
  36:         fprintf(stderr, "Failed to set error buffer [%d]n", code);
  37:         return false;
  38:     }
  39:     code = curl_easy_setopt(conn, CURLOPT_URL, url);
  40:     if (code != CURLE_OK)
  41:     {
  42:         fprintf(stderr, "Failed to set URL [%s]n", errorBuffer);
  43:         return false;
  44:     }
  45:     code = curl_easy_setopt(conn, CURLOPT_FOLLOWLOCATION, 1);
  46:     if (code != CURLE_OK)
  47:     {
  48:         fprintf(stderr, "Failed to set redirect option [%s]n", errorBuffer);
  49:         return false;
  50:     }
  51:     code = curl_easy_setopt(conn, CURLOPT_WRITEFUNCTION, writer);
  52:     if (code != CURLE_OK)
  53:     {
  54:         fprintf(stderr, "Failed to set writer [%s]n", errorBuffer);
  55:         return false;
  56:     }
  57:     code = curl_easy_setopt(conn, CURLOPT_WRITEDATA, p_buffer);
  58:     if (code != CURLE_OK)
  59:     {
  60:         fprintf(stderr, "Failed to set write data [%s]n", errorBuffer);
  61:         return false;
  62:     }
  63:     return true;
  64: }
  65:
  66: static int writer(char *data, size_t size, size_t nmemb, string *writerData)
  67: {
  68:     unsigned long sizes = size * nmemb;
  69:     if (writerData == NULL) return 0;
  70:     writerData->append(data, sizes);
  71:     return sizes;
  72: }