C語(yǔ)言是一門廣泛應(yīng)用于系統(tǒng)編程和嵌入式開(kāi)發(fā)領(lǐng)域的編程語(yǔ)言,C語(yǔ)言中有一種叫做POST的方法,可以用于向Web服務(wù)器發(fā)送數(shù)據(jù)。而JSON是一種數(shù)據(jù)格式,用于存儲(chǔ)和交換數(shù)據(jù)。在C語(yǔ)言中,我們可以使用POST方法來(lái)獲取JSON數(shù)據(jù)類型。
#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庫(kù)發(fā)送HTTP POST請(qǐng)求,將服務(wù)器返回的響應(yīng)數(shù)據(jù)存儲(chǔ)在一個(gè)內(nèi)存塊中。然后,我們使用JSON-C庫(kù)將內(nèi)存塊中的JSON數(shù)據(jù)類型解析為json_object對(duì)象,并將其轉(zhuǎn)換為字符串輸出。