在使用C語言開發(fā)Web應用時,可能需要獲取從URL傳過來的JSON數(shù)據(jù)。可以使用以下代碼實現(xiàn):
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <curl/curl.h> 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_global_init(CURL_GLOBAL_ALL); curl_handle = curl_easy_init(); curl_easy_setopt(curl_handle, CURLOPT_URL, "https://example.com/json_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)); } else { printf("%lu bytes retrieved\n", (unsigned long)chunk.size); printf("JSON Data:\n%s\n", chunk.memory); } curl_easy_cleanup(curl_handle); if (chunk.memory) { free(chunk.memory); } curl_global_cleanup(); return 0; }
在上述代碼中,我們使用C語言的curl庫獲取URL傳過來的JSON數(shù)據(jù)。我們定義了一個結構體MemoryStruct來表示數(shù)據(jù),使用realloc來動態(tài)分配內存存儲數(shù)據(jù),使用curl_easy_setopt函數(shù)設置URL和回調函數(shù)、用戶數(shù)據(jù)等信息,最終通過curl_easy_perform函數(shù)執(zhí)行請求。如果請求成功,就可以在回調函數(shù)中獲取JSON數(shù)據(jù)。