在c語言中,有時候我們需要從url中獲取傳過來的json數據,這時候我們可以使用一些常見的庫來實現這個功能。
#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); /* 初始化一個curl比手動賦值快得多 */ curl_handle = curl_easy_init(); /* 設置url */ curl_easy_setopt(curl_handle, CURLOPT_URL, "https://jsonplaceholder.typicode.com/todos/1"); /* 設置http請求頭 */ struct curl_slist *headers = NULL; headers = curl_slist_append(headers, "Content-Type: application/json"); curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, headers); /* 設置回調函數 */ curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); /* 將回調函數數據交給curl */ curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk); /* 執行curl請求 */ res = curl_easy_perform(curl_handle); /* 檢查curl請求是否成功 */ 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請求頭資源 */ curl_slist_free_all(headers); /* 釋放回調函數數據 */ free(chunk.memory); /* 清理全局curl資源 */ curl_global_cleanup(); return 0; }
上面的代碼中,我們先使用curl_global_init()初始化curl,然后初始化一個curl_easy_init(),設置url和http請求頭,接著設置一個回調函數,最后執行curl請求并檢查請求是否成功。我們可以在回調函數中查看是否獲取到json數據。
上一篇vue 怎么刷新數據
下一篇vue 對價格過濾