Permalink
Browse files

Initial commit. Depends on libcurl, no Makefile.

  • Loading branch information...
0 parents commit 5bd9ac321453d4a81fc7fb4f351f8d2cd521bd30 @ebobby committed Dec 15, 2011
Showing with 88 additions and 0 deletions.
  1. +2 −0 .gitignore
  2. +53 −0 requests.c
  3. +16 −0 stackoverflow-cli.c
  4. +17 −0 stackoverflow-cli.h
@@ -0,0 +1,2 @@
+*.o
+stackoverflow-cli
@@ -0,0 +1,53 @@
+#include "stackoverflow-cli.h"
+
+#include <curl/curl.h>
+
+static size_t request_callback (char *ptr, size_t size, size_t nmemb, void *usr) {
+ size_t realsize = size * nmemb;
+ responseObject *response = (responseObject *)usr;
+
+ if (realsize != 0) {
+ response->data = (char *)malloc(realsize + 1);
+
+ if (response->data == NULL) {
+ printf("Not enough memory!");
+ exit(EXIT_FAILURE);
+ }
+
+ memcpy((void *)response->data, (void *)ptr, realsize);
+ response->data[realsize] = 0;
+ response->size = realsize;
+ } else {
+ response->data = NULL;
+ response->size = 0;
+ }
+
+ return realsize;
+}
+
+void www_make_request (char *url, responseObject *response) {
+ CURL *curlHandle = NULL;
+
+ curl_global_init(CURL_GLOBAL_ALL);
+
+ curlHandle = curl_easy_init();
+
+ curl_easy_setopt(curlHandle, CURLOPT_URL, url);
+ curl_easy_setopt(curlHandle, CURLOPT_ACCEPT_ENCODING, "\0");
+ curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, request_callback);
+ curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, (void *)response);
+
+ curl_easy_perform(curlHandle);
+
+ curl_easy_cleanup(curlHandle);
+}
+
+void www_free_response (responseObject *response) {
+ if (response == NULL)
+ return;
+
+ if (response->data != NULL)
+ free(response->data);
+
+ response->size = 0;
+}
@@ -0,0 +1,16 @@
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "stackoverflow-cli.h"
+
+int main (void) {
+ responseObject response;
+
+ www_make_request("http://api.stackoverflow.com/1.1/questions?pagesize=2", &response);
+
+ printf("Stackoverflow result:\n%s\n", response.data);
+
+ www_free_response(&response);
+
+ return 0;
+}
@@ -0,0 +1,17 @@
+#ifndef __STACKOVERFLOW_H__
+#define __STACKOVERFLOW_H__
+
+#include <stdlib.h>
+#include <string.h>
+
+/** Helpers from requests.c *****************************/
+typedef struct responseObject {
+ size_t size;
+ char *data;
+} responseObject;
+
+void www_make_request (char *url, responseObject *response);
+void www_free_response (responseObject *response);
+/********************************************************/
+
+#endif

0 comments on commit 5bd9ac3

Please sign in to comment.