Created
August 9, 2011 17:51
-
-
Save 9re/1134706 to your computer and use it in GitHub Desktop.
libcurl test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
test: test.c | |
gcc -o test test.c -lcurl |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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