C語言作為一門廣泛應用的編程語言,其內置函數庫也相當豐富。對于開發人員而言,有時候需要接收JSON數據類型的POST請求。接下來,我們將通過C語言的內置函數庫來實現這個需求。
#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) return 0; memcpy(&(mem->memory[mem->size]), contents, realsize); mem->size += realsize; mem->memory[mem->size] = 0; return realsize; } int main(void) { CURL *curl; CURLcode res; curl = curl_easy_init(); if(curl) { struct MemoryStruct chunk; chunk.memory = malloc(1); chunk.size = 0; curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/receivejson"); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "{\"key\":\"value\"}"); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk); res = curl_easy_perform(curl); 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); free(chunk.memory); curl_easy_cleanup(curl); } return 0; }
在上述代碼中,我們首先引入了“curl/curl.h”頭文件,來實現CURL發送POST請求。接下來,創建了一個WriteMemoryCallback函數來存儲接收到的JSON數據。使用curl_easy_setopt方法設置請求的URL、POST數據、回調函數和回調參數。最后通過curl_easy_perform方法發送請求??梢钥吹?,使用C語言非常簡單地實現了接收JSON數據類型的POST請求的功能。