c語(yǔ)言可以通過(guò)post方式將json數(shù)據(jù)發(fā)送至服務(wù)器中,post方式發(fā)送的數(shù)據(jù)需要在http請(qǐng)求中添加表頭部分。表頭部分包括Content-Type和Content-Length兩個(gè)參數(shù)。
#include <stdlib.h> #include <stdio.h> #include <curl/curl.h> int main(int argc, char *argv[]) { CURL *curl; CURLcode res; curl_global_init(CURL_GLOBAL_DEFAULT); curl = curl_easy_init(); if(curl) { curl_easy_setopt(curl, CURLOPT_URL, "http://example.com"); curl_easy_setopt(curl, CURLOPT_POST, 1); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "json={\"name\":\"Jack\",\"age\":28}"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, "Content-Type: application/json"); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, 30L); res = curl_easy_perform(curl); if(res != CURLE_OK) fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); curl_easy_cleanup(curl); } curl_global_cleanup(); return 0; }
在上述代碼中,通過(guò)curl_easy_setopt函數(shù)設(shè)置了post請(qǐng)求方式、添加了json數(shù)據(jù)、設(shè)置了Content-Type為application/json、設(shè)置Content-Length為30字節(jié)。