Using HTTP authentication with libcurl in C for Tw

2019-02-15 19:04发布

Possible Duplicate:
Trying to Access Twitter Streaming API with C

I am not sure what I am doing wrong in my code but it seems there's a problem on authentication. Every time I execute the code there is no output.

My goal here is I wanted to receive a stream of Tweets from Twitter API. The problem might be something else. But I am not sure. Please help.

This is the C code:

#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:password_here");
    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;
}

1条回答
该账号已被封号
2楼-- · 2019-02-15 19:48
  1. Use ssl.
  2. You could use curl_easy_strerror() to get a human readable error message:

    printf("curl error %s", curl_easy_strerror(res));
    
  3. You'll run out of memory after a while (at my end the stream is ~250Kb/s). Save interesting info to a persistent storage and discard the rest.
查看更多
登录 后发表回答