cURL / Mailing Lists / curl-library / Single Mail

curl-library

Regular HTTP POST using callback

From: Daniel Stenberg <daniel_at_haxx.se>
Date: Thu, 14 Mar 2002 01:15:28 +0100 (MET)

Yeps

I just fixed my libcurl to support HTTP POST data to get read off a read
callback (the ordinary read-callback way) and it seems to work (code follows
below to illustrate my point). This code is not in CVS just yet.

I intend to take this one step further now, to send the entire HTTP request
this way using what can be seen as an internal callback. It will make a much
better system for dealing with EWOULDBLOCK situations and similar.

/*****************************************************************************
 * _ _ ____ _
 * Project ___| | | | _ \| |
 * / __| | | | |_) | |
 * | (__| |_| | _ <| |___
 * \___|\___/|_| \_\_____|
 *
 * $Id: http-post.c,v 1.1 2002/01/10 09:00:02 bagder Exp $
 */

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

char data[]="this is what we post to the silly web server";

struct WriteThis {
  char *readptr;
  int sizeleft;
};

size_t read_callback(void *ptr, size_t size, size_t nmemb, void *userp)
{
  struct WriteThis *pooh = (struct WriteThis *)userp;

  if(size*nmemb < 1)
    return 0;

  if(pooh->sizeleft) {
    *(char *)ptr = pooh->readptr[0]; /* copy one single byte */
    pooh->readptr++; /* advance pointer */
    pooh->sizeleft--; /* less data left */
    fprintf(stderr, "PASSED %c\n", *(char *)ptr);
    return 1; /* we return 1 byte at a time! */
  }

  fprintf(stderr, "DONE\n");
  return -1; /* no data left to deliver */
}

int main(void)
{
  CURL *curl;
  CURLcode res;

  struct WriteThis pooh;

  pooh.readptr = data;
  pooh.sizeleft = strlen(data);

  curl = curl_easy_init();
  if(curl) {
    /* First set the URL that is about to receive our POST. */
    curl_easy_setopt(curl, CURLOPT_URL,
                     "http://www.contactor.se/~dast/");
    /* Now specify we want to POST data */
    curl_easy_setopt(curl, CURLOPT_POST, TRUE);

    /* Set the expected POST size */
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, pooh.sizeleft);

    /* we want to use our own read function */
    curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);

    /* pointer to pass to our read function */
    curl_easy_setopt(curl, CURLOPT_INFILE, &pooh);

    /* get verbose debug output please */
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);

    /* Perform the request, res will get the return code */
    res = curl_easy_perform(curl);

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

-- 
    Daniel Stenberg -- curl groks URLs -- http://curl.haxx.se/
Received on 2002-03-14