C Studio 是一款流行的開發工具,它能夠讓開發者更加方便地進行編程工作。在一些應用開發場景中,需要通過請求 JSON 數據來進行一些操作。接下來,將介紹如何在 C Studio 中請求 JSON 數據。
#include#include #include #include typedef struct { char *memory; size_t size; }MemoryStruct; static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { size_t realsize = size * nmemb; MemoryStruct *mem = (MemoryStruct *)userp; char *ptr = (char *)realloc(mem->memory, mem->size + realsize + 1); if (ptr == NULL) { 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(void) { CURL *curl_handle; CURLcode res; MemoryStruct chunk; chunk.memory = (char *)malloc(1); chunk.size = 0; curl_global_init(CURL_GLOBAL_ALL); curl_handle = curl_easy_init(); curl_easy_setopt(curl_handle, CURLOPT_URL, "http://my-json-server.typicode.com/typicode/demo/posts"); 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("%.*s", chunk.size, chunk.memory); } curl_easy_cleanup(curl_handle); free(chunk.memory); curl_global_cleanup(); return 0; }
以上代碼通過調用 cURL 庫來進行 HTTP 請求,并將獲取到的內容存儲在內存中。開發者可以根據自己的需求對此代碼進行修改和擴展,以實現自己的應用場景。