在c語(yǔ)言中,有時(shí)候我們需要從url中獲取傳過(guò)來(lái)的json數(shù)據(jù),這時(shí)候我們可以使用一些常見(jiàn)的庫(kù)來(lái)實(shí)現(xiàn)這個(gè)功能。
#include#include #include #include struct MemoryStruct { char *memory; size_t size; }; static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { size_t realsize = size * nmemb; struct MemoryStruct *mem = (struct MemoryStruct *)userp; mem->memory = realloc(mem->memory, mem->size + realsize + 1); if (mem->memory == NULL) { /* out of memory! */ printf("not enough memory (realloc returned NULL)\n"); return 0; } memcpy(&(mem->memory[mem->size]), contents, realsize); mem->size += realsize; mem->memory[mem->size] = 0; return realsize; } int main(void) { CURL *curl_handle; CURLcode res; struct MemoryStruct chunk; chunk.memory = malloc(1); chunk.size = 0; /* 初始化curl */ curl_global_init(CURL_GLOBAL_ALL); /* 初始化一個(gè)curl比手動(dòng)賦值快得多 */ curl_handle = curl_easy_init(); /* 設(shè)置url */ curl_easy_setopt(curl_handle, CURLOPT_URL, "https://jsonplaceholder.typicode.com/todos/1"); /* 設(shè)置http請(qǐng)求頭 */ struct curl_slist *headers = NULL; headers = curl_slist_append(headers, "Content-Type: application/json"); curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, headers); /* 設(shè)置回調(diào)函數(shù) */ curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); /* 將回調(diào)函數(shù)數(shù)據(jù)交給curl */ curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk); /* 執(zhí)行curl請(qǐng)求 */ res = curl_easy_perform(curl_handle); /* 檢查curl請(qǐng)求是否成功 */ if (res != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); } else { printf("%s\n", chunk.memory); } /* 清理curl資源 */ curl_easy_cleanup(curl_handle); /* 清理http請(qǐng)求頭資源 */ curl_slist_free_all(headers); /* 釋放回調(diào)函數(shù)數(shù)據(jù) */ free(chunk.memory); /* 清理全局curl資源 */ curl_global_cleanup(); return 0; }
上面的代碼中,我們先使用curl_global_init()初始化curl,然后初始化一個(gè)curl_easy_init(),設(shè)置url和http請(qǐng)求頭,接著設(shè)置一個(gè)回調(diào)函數(shù),最后執(zhí)行curl請(qǐng)求并檢查請(qǐng)求是否成功。我們可以在回調(diào)函數(shù)中查看是否獲取到j(luò)son數(shù)據(jù)。