Skip to content

Instantly share code, notes, and snippets.

@9re
Created August 9, 2011 17:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 9re/1134706 to your computer and use it in GitHub Desktop.
Save 9re/1134706 to your computer and use it in GitHub Desktop.
libcurl test
test: test.c
gcc -o test test.c -lcurl
#include <curl/curl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct {
int statusCode;
char *body;
} Response;
size_t static callback(void *ptr, size_t size, size_t nmemb, void *userdata) {
static int index = 0;
Response *response = (Response*) userdata;
memcpy(response->body + index, ptr, nmemb);
char sample[10];
strncpy(sample, (char *)ptr, 9);
sample[9] = '\0';
printf("got the line begin with: %s\n", sample);
index += nmemb;
return size * nmemb;
}
int main(int argc, char **argv) {
CURL *curl = curl_easy_init();
if (curl) {
char* url = "http://www.ietf.org/rfc/rfc2396.txt";
Response *response = malloc(sizeof(Response));
response->body = malloc(1024 * 1024);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, response);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback);
curl_easy_setopt(curl, CURLOPT_URL, url);
CURLcode code = curl_easy_perform(curl);
if (code == CURLE_WRITE_ERROR) {
printf("error occurred!");
} else {
printf("response code:%d", code);
}
printf("total bytes:%d", strlen(response->body));
free(response->body);
free(response);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment