在C語(yǔ)言的Web開發(fā)中,我們會(huì)經(jīng)常使用POST請(qǐng)求發(fā)送數(shù)據(jù)到服務(wù)器。這里介紹一個(gè)實(shí)用的方法,將POST請(qǐng)求參數(shù)轉(zhuǎn)為JSON數(shù)據(jù)格式,方便進(jìn)行后續(xù)的數(shù)據(jù)處理。
首先需要引入頭文件
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <jansson.h>
#include <curl/curl.h>
然后我們需要定義一個(gè)回調(diào)函數(shù)來(lái)獲取服務(wù)器返回的數(shù)據(jù)。
static size_t write_callback(char *ptr, size_t size, size_t nmemb, void *data) {
size_t realsize = size * nmemb;
char *temp = realloc(data, strlen(data) + realsize + 1);
if (temp == NULL) {
fprintf(stderr, "realloc failed\n");
return 0;
}
data = temp;
strncat(data, ptr, realsize);
return realsize;
}
接下來(lái),我們需要使用curl庫(kù)來(lái)發(fā)送POST請(qǐng)求,并將請(qǐng)求參數(shù)轉(zhuǎn)為JSON格式。下面是具體的代碼:
// 定義發(fā)送的數(shù)據(jù)
char *post_data = "name=Tom&age=20&gender=Male";
// 轉(zhuǎn)為JSON格式
json_t *json_obj = json_object();
char *split = strtok(post_data, "&");
while (split != NULL) {
char *key = strtok(split, "=");
char *value = strtok(NULL, "=");
json_object_set(json_obj, key, json_string(value));
split = strtok(NULL, "&");
}
char* data = json_dumps(json_obj, 0);
// 設(shè)置發(fā)送的請(qǐng)求頭和數(shù)據(jù)
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Content-Type: application/json");
CURL *curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_URL, "http://localhost:8080/path");
curl_easy_setopt(curl, CURLOPT_POST, 1L);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
// 發(fā)送POST請(qǐng)求
char *response = (char*)malloc(1);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)response);
curl_easy_perform(curl);
response = realloc(response, strlen(response) + 1);
curl_easy_cleanup(curl);
// 處理服務(wù)器返回?cái)?shù)據(jù)
json_error_t error;
json_t *result = json_loads(response, 0, &error);
// 釋放內(nèi)存
free(post_data);
json_decref(json_obj);
free(data);
free(response);
以上是在C語(yǔ)言中實(shí)現(xiàn)POST請(qǐng)求參數(shù)轉(zhuǎn)JSON數(shù)據(jù)的完整代碼。通過這種方式,我們可以方便地發(fā)送POST請(qǐng)求并將請(qǐng)求參數(shù)轉(zhuǎn)換為JSON格式,便于后續(xù)的數(shù)據(jù)處理。