C語言是一種廣泛使用的編程語言,能夠完成各種各樣的任務。在網絡開發中,C語言也有很多應用,例如獲取HTTP接口數據。
在C語言中,我們可以使用libcurl庫來進行HTTP請求。同時,我們可以使用cJSON庫來解析JSON數據。
#include#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"); exit(EXIT_FAILURE); } 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_global_init(CURL_GLOBAL_ALL); curl_handle = curl_easy_init(); curl_easy_setopt(curl_handle, CURLOPT_URL, "https://example.com/api/data"); curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk); res = curl_easy_perform(curl_handle); if (res != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); exit(EXIT_FAILURE); } cJSON *json = cJSON_Parse(chunk.memory); if (json == NULL) { const char *error_ptr = cJSON_GetErrorPtr(); if (error_ptr != NULL) { fprintf(stderr, "Error before: %s\n", error_ptr); } exit(EXIT_FAILURE); } cJSON *data = cJSON_GetObjectItemCaseSensitive(json, "data"); if (!cJSON_IsArray(data)) { exit(EXIT_FAILURE); } cJSON_ArrayForEach(data_item, data) { cJSON *name = cJSON_GetObjectItemCaseSensitive(data_item, "name"); cJSON *age = cJSON_GetObjectItemCaseSensitive(data_item, "age"); printf("%s is %d years old.\n", name->valuestring, age->valueint); } cJSON_Delete(json); curl_easy_cleanup(curl_handle); curl_global_cleanup(); return 0; }
上面的代碼演示了如何通過HTTP請求獲取JSON數據,并使用cJSON庫解析數據。其中,我們使用了chunk結構體來保存HTTP響應數據,使用curl_easy_setopt()函數設置請求URL、保存HTTP響應數據的回調函數和回調函數的參數等。
最后,我們使用cJSON庫的函數來解析JSON數據,并打印出其中的name和age字段。
上一篇mysql跨庫視圖