【问题标题】:Trying to Access Twitter Streaming API with C尝试使用 C 访问 Twitter 流 API
【发布时间】:2011-12-26 22:20:45
【问题描述】:

我从C libcurl get output into a string 获得了代码。我修改了它,我想用它来访问 Twitter 流。我在代码中添加了curl_easy_setopt(curl, CURLOPT_URL, "http://stream.twitter.com/1/statuses/sample.json");curl_easy_setopt(curl, CURLOPT_USERPWD, "neilmarion:my_password");。但问题是每当我执行它时,都没有输出。一定是什么问题?谢谢。

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

struct string {
  char *ptr;
  size_t len;
};

void init_string(struct string *s) {
  s->len = 0;
  s->ptr = malloc(s->len+1);
  if (s->ptr == NULL) {
    fprintf(stderr, "malloc() failed\n");
    exit(EXIT_FAILURE);
  }
  s->ptr[0] = '\0';
}

size_t writefunc(void *ptr, size_t size, size_t nmemb, struct string *s)
{
  size_t new_len = s->len + size*nmemb;
  s->ptr = realloc(s->ptr, new_len+1);
  if (s->ptr == NULL) {
    fprintf(stderr, "realloc() failed\n");
    exit(EXIT_FAILURE);
  }
  memcpy(s->ptr+s->len, ptr, size*nmemb);
  s->ptr[new_len] = '\0';
  s->len = new_len;

  return size*nmemb;
}

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

  curl = curl_easy_init();
  if(curl) {
    struct string s;
    init_string(&s);

    curl_easy_setopt(curl, CURLOPT_URL, "http://stream.twitter.com/1/statuses/sample.json");
    curl_easy_setopt(curl, CURLOPT_USERPWD, "neilmarion:my_password");
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s);
    res = curl_easy_perform(curl);

    printf("%s\n", s.ptr);
    free(s.ptr);

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

【问题讨论】:

  • 转接后“res”的值是多少? curL_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);的值怎么样

标签: c twitter curl stream


【解决方案1】:

最快的下一步可能是设置 CURLOPT_HEADER,以在正文输出中包含标题。很可能,我猜它在安全方面失败了,你会在标题中看到详细信息。

【讨论】:

  • 先生,你能告诉我如何使用这个 'curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc);' ?我相信'writefunc'必须有一个回调函数。但我不确定如何编码。谢谢。
  • 我认为您正确使用了它 - 事实上我认为它比我之前所做的更好,因为我没有看到 WRITEDATA 选项,而是使用全局变量。无论哪种方式,我在这里都使用了一个示例回调函数:stackoverflow.com/questions/7850716/…
猜你喜欢
  • 2011-06-11
  • 1970-01-01
  • 2015-03-06
  • 2016-02-03
  • 1970-01-01
  • 1970-01-01
  • 2020-02-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多