1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
| #include <stdio.h> #include <stdlib.h> #include <string.h> #include <curl/curl.h>
struct MemoryStruct { char *memory; size_t size; };
size_t write_callback(char *contents, size_t size, size_t nmemb, void *userp){ size_t realsize = size * nmemb; struct MemoryStruct *mem = (struct MemoryStruct *)userp;
char *ptr = realloc(mem->memory, mem->size + realsize + 1); if(!ptr) { printf("not enough memory (realloc returned NULL)\n"); return 0; }
mem->memory = ptr; memcpy(&(mem->memory[mem->size]), contents, realsize); mem->size += realsize; mem->memory[mem->size] = 0;
return realsize; }
int main(){ CURL *curl; CURLcode res;
if (CURLE_OK != (res = curl_global_init(CURL_GLOBAL_ALL))) { printf("CURL Global Init fail\r\n"); return 1; } curl = curl_easy_init(); if (curl == NULL) { printf("CURL easy Init fail\r\n"); return 1; }
curl_easy_setopt(curl, CURLOPT_URL, "http://localhost"); curl_easy_setopt(curl, CURLOPT_PORT, 8000);
struct curl_slist *hs=NULL; hs = curl_slist_append(hs, "Content-Type: application/json"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, hs); struct MemoryStruct chunk; chunk.memory = malloc(1); chunk.size = 0; curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
res = curl_easy_perform(curl); if(res != CURLE_OK) { printf("CURL curl_easy_perform fail: %s\r\n", curl_easy_strerror(res)); return 1; } else{ printf("Response data:\r\n"); printf("%s\n",chunk.memory); }
curl_easy_reset(curl);
curl_easy_setopt(curl, CURLOPT_URL, "http://localhost"); curl_easy_setopt(curl, CURLOPT_PORT, 8000); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, hs); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "{\"sendData\":\"dataContent\"}"); chunk.memory = malloc(1); chunk.size = 0; curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk); res = curl_easy_perform(curl); if(res != CURLE_OK) { printf("CURL curl_easy_perform fail: %s\r\n", curl_easy_strerror(res)); return 1; } else{ printf("Response data:\r\n"); printf("%s\n",chunk.memory); }
curl_easy_cleanup(curl); return 0; }
|