C語言是一種強大的編程語言,其應用場景廣泛,使用范圍極廣。本文將介紹如何使用C語言獲取POST請求中的JSON數據。
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> struct Memory { char *memory; size_t size; }; static size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata) { struct Memory *mem = (struct Memory *)userdata; size_t realsize = size * nmemb; mem->memory = realloc(mem->memory, mem->size + realsize + 1); if (mem->memory) { memcpy(&(mem->memory[mem->size]), ptr, realsize); mem->size += realsize; mem->memory[mem->size] = 0; } return realsize; } char *get_post_json(char *url, char *post_data) { CURL *curl; CURLcode res; char *response = NULL; struct Memory chunk = {0}; curl_global_init(CURL_GLOBAL_DEFAULT); curl = curl_easy_init(); if (curl) { struct curl_slist *headers = NULL; headers = curl_slist_append(headers, "Content-Type: application/json"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_data); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk); res = curl_easy_perform(curl); curl_easy_cleanup(curl); response = chunk.memory; curl_slist_free_all(headers); } curl_global_cleanup(); return response; }
該代碼使用了libcurl庫來執(zhí)行HTTP請求。GET和POST都可以使用該庫來處理,而且非常簡單。通過調用curl_easy_setopt函數設置請求的類型、目標URL、請求正文以及回調函數以獲取響應。在本例中,收到的JSON響應將存儲在一個內存塊中,之后我們可以使用該響應進行后續(xù)操作。