在C語言中,我們可以通過POST方式獲取JSON數據類型的信息。具體的實現過程如下:
#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) { printf("ERROR: 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, "http://example.com/api"); curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDS, "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}"); 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) { printf("curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); } else { printf("%lu bytes retrieved\n", (unsigned long)chunk.size); printf("%s\n", chunk.memory); } curl_easy_cleanup(curl_handle); free(chunk.memory); curl_global_cleanup(); return 0; }
以上代碼中,我們使用了libcurl庫來構建C程序,用于通過POST方式獲取JSON數據類型的信息。在代碼中,我們先定義了一個結構體`MemoryStruct`,用于存儲獲取的數據。然后,我們在main函數中,創建了一個`curl_handle`句柄,用于發送POST請求。同時,我們將JSON數據類型的信息作為POST請求提交到指定的URL。獲取到數據后,通過`WriteMemoryCallback`函數將數據存儲到`MemoryStruct`結構體中。最后,我們通過printf函數輸出獲取到的數據。