[C Program] curl example code.
ITWeb/개발일반 2012. 5. 22. 00:22[Source Link]
http://curl.haxx.se/libcurl/c/
[Source Code]
// http://curl.haxx.se/libcurl/c/example.html
// http://curl.haxx.se/libcurl/c/curl_easy_setopt.html
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
typedef struct curlResponseData {
char *response;
size_t size;
}CURL_RES_DATA;
void initCurlResponseData (CURL_RES_DATA *res) {
res->size = 0;
res->response = malloc(res->size+1);
if ( res->response == NULL ) {
fprintf(stderr, "malloc() failed\n");
exit(EXIT_FAILURE);
}
res->response[0] = '\0';
}
size_t curlWriteFunction (void *ptr, size_t size, size_t nmemb, CURL_RES_DATA *res) {
size_t newLen = res->size + size*nmemb;
res->response = realloc(res->response, newLen+1);
if (res->response == NULL) {
fprintf(stderr, "realloc() failed\n");
exit(EXIT_FAILURE);
}
memcpy(res->response+res->size, ptr, size*nmemb);
res->response[newLen] = '\0';
res->size = newLen;
return size*nmemb;
}
int main(int argc, char *argv[]) {
CURL *curl;
CURLcode res;
CURL_RES_DATA resData;
initCurlResponseData(&resData);
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://www.example.com");
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &resData);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curlWriteFunction);
if ( (res = curl_easy_perform(curl)) == 0 ) {
printf("Everything is OK.\n");
printf("%s\n", resData.response);
}
free(resData.response);
/* always cleanup */
curl_easy_cleanup(curl);
}
return 0;
}
[Build]
- 위치
mkdir -p /home/jjeong/workspace/curl
cd /home/jjeong/workspace/curl
- prerequisite
http://curl.haxx.se/
http://curl.haxx.se/libcurl/c/
curl-7.25.0.tar.gz
tar -xvzf curl-7.25.0.tar.gz
ln curl-7.25.0 curl
- gcc
gcc curlExample.c ./curl/lib/.libs/libcurl.a -I./curl/include -lssl -lrt -o curlExample