使用 libcurl 和 C 访问 Twitter Streaming API

发布于 2024-10-14 01:59:18 字数 839 浏览 5 评论 0原文

我正在尝试用 C 语言编写一个程序,该程序将从流 API 中获取每条推文并将其存储在数据库中。但是,我无法让它工作,我使用下面的代码:

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


size_t callback_func(void *ptr, size_t size, size_t count, void *stream) {
  /* ptr - your string variable.
  stream - data chuck you received */
printf("res %s \n \n", (char*)ptr); //prints chunck of data for each call.

}

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

  curl = curl_easy_init();
  if(curl) {
   curl_easy_setopt(curl, CURLOPT_URL, "http://google.com/");
    //curl_easy_setopt(curl, CURLOPT_USERPWD, "JEggers2:password");
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback_func);
    curl_easy_perform(curl);

    /* always cleanup */ 
     curl_easy_cleanup(curl);


  }


  return 0;
}

此代码仅以 JSON 格式输出一条推文。我做错了什么?谢谢

I'm trying to write a program in C which will take each tweet from the streaming API and store it in a database. However, I can't get it to work, I'm using the below code:

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


size_t callback_func(void *ptr, size_t size, size_t count, void *stream) {
  /* ptr - your string variable.
  stream - data chuck you received */
printf("res %s \n \n", (char*)ptr); //prints chunck of data for each call.

}

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

  curl = curl_easy_init();
  if(curl) {
   curl_easy_setopt(curl, CURLOPT_URL, "http://google.com/");
    //curl_easy_setopt(curl, CURLOPT_USERPWD, "JEggers2:password");
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback_func);
    curl_easy_perform(curl);

    /* always cleanup */ 
     curl_easy_cleanup(curl);


  }


  return 0;
}

This code only outputs one tweet in JSON format. What am I doing wrong? thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

_蜘蛛 2024-10-21 01:59:18

问题是 callback_func 不返回任何内容。

根据 规范,如果读取成功。

函数指针应符合以下原型: size_t function( void *ptr, size_t size, size_t nmemb, void *userdata);一旦收到需要保存的数据,libcurl 就会调用该函数。 ptr指向的数据大小是size乘以nmemb,不会以零结尾。返回实际处理的字节数。如果该金额与传递给函数的金额不同,则会向库发出错误信号。这将中止传输并返回 CURLE_WRITE_ERROR。

The problem is that callback_func does not return anything.

According to the spec, you should return size if the read was successful.

Function pointer that should match the following prototype: size_t function( void *ptr, size_t size, size_t nmemb, void *userdata); This function gets called by libcurl as soon as there is data received that needs to be saved. The size of the data pointed to by ptr is size multiplied with nmemb, it will not be zero terminated. Return the number of bytes actually taken care of. If that amount differs from the amount passed to your function, it'll signal an error to the library. This will abort the transfer and return CURLE_WRITE_ERROR.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文