C語言是一門廣泛應用于系統編程和嵌入式開發領域的編程語言,C語言中有一種叫做POST的方法,可以用于向Web服務器發送數據。而JSON是一種數據格式,用于存儲和交換數據。在C語言中,我們可以使用POST方法來獲取JSON數據類型。
#include#include #include #include #define URL "http://example.com" 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("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, URL); 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)); } curl_easy_cleanup(curl_handle); json_object *jobj = json_tokener_parse(chunk.memory); printf("JSON data: %s\n", json_object_to_json_string(jobj)); free(chunk.memory); curl_global_cleanup(); return 0; }
上述代碼中,我們使用CURL庫發送HTTP POST請求,將服務器返回的響應數據存儲在一個內存塊中。然后,我們使用JSON-C庫將內存塊中的JSON數據類型解析為json_object對象,并將其轉換為字符串輸出。