CURL的回读功能

时间:2014-09-25 23:05:12

标签: curl libcurl

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

    struct WriteThis {
      const char *readptr;
      long sizeleft;
    };
    static 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 */ 
        return 1;                        /* we return 1 byte at a time! */ 
      }

      return 0;                          /* no more data left to deliver */ 
    }

 struct WriteThis pooh;

  pooh.readptr = data;
  pooh.sizeleft = (long)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://example.com/index.cgi");

        /* Now specify we want to POST data */ 
        curl_easy_setopt(curl, CURLOPT_POST, 1L);

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



    };

我没看到read_callback()的参数是如何初始化的。 ptr,size和nmmemb以及usurp。

1 个答案:

答案 0 :(得分:2)

正如CURL文档所说,read_callback是一个回调函数,一旦需要读取数据就会被libcurl调用,以便将其发送给对等体。 size_t nmemb表示curl已为单个数据块保留的大小,最后void* userp是由CURLOPT_READDATA选项设置的指针,因此您需要在代码中添加此行:< / p>

curl_easy_setopt(curl, CURLOPT_READDATA, &pooh);

不要忘记最后致电curl_easy_perform(curl)