echo Impossible|sed 's/Im/To be /'

December 05, 2010

Tip. libcurl example

libcurl http example code


curl 是 Unix 上的 power tools,常用來作 http https ftp 連接。libcurl 是 curl 的 library 提供了好用的 API, 好好運用可以省去不少瑣事。


以下範例由 libcurl examples code fopen.c sepheaders.c 節錄並稍作整理作為記錄

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <curl/curl.h>

struct fcurl_data {
    char *buffer;             /* buffer to store cached data */
    int buffer_len;           /* currently allocated buffers length */
    int buffer_pos;           /* end of data in buffer */
};

typedef struct fcurl_data URL_FILE;

static size_t
write_callback(char *buffer, size_t size, size_t nitems, void *userp)
{
    char *newbuff;
    int rembuff;

    URL_FILE *url = (URL_FILE *) userp;
    size *= nitems;

    rembuff = url->buffer_len - url->buffer_pos;      /* remaining space in buffer */

    if (size > rembuff) {
      /* not enough space in buffer */
      newbuff = realloc(url->buffer, url->buffer_len + (size - rembuff));
      if (newbuff == NULL) {
          fprintf(stderr, "callback buffer grow failed\n");
          size = rembuff;
      } else {
          /* realloc suceeded increase buffer size */
          url->buffer_len += size - rembuff;
          url->buffer = newbuff;
      }
    }

    memcpy(&url->buffer[url->buffer_pos], buffer, size);
    url->buffer_pos += size;

    return size;
}

int main(void)
{
    CURL *curl;
    CURLcode res;
    URL_FILE *htmlbody, *htmlheader;

    htmlbody = malloc(sizeof(URL_FILE));
    htmlheader = malloc(sizeof(URL_FILE));
    memset(htmlbody, 0, sizeof(URL_FILE));
    memset(htmlheader, 0, sizeof(URL_FILE));

    curl = curl_easy_init();
    if (curl) {
      curl_easy_setopt(curl, CURLOPT_URL, "http://127.0.0.1/");
      curl_easy_setopt(curl, CURLOPT_PORT, 80);
      curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L);
      curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
      curl_easy_setopt(curl, CURLOPT_WRITEDATA, htmlbody);
      curl_easy_setopt(curl, CURLOPT_WRITEHEADER, htmlheader);
      res = curl_easy_perform(curl);
      printf("body: %s\n\n", htmlbody->buffer);
      printf("header: %s\n", htmlheader->buffer);

      /* always cleanup */
      curl_easy_cleanup(curl);
    }
    return 0;
}

Makefile

gcc -o curlsample curlsample.c -l curl