C語(yǔ)言中,通過http協(xié)議傳輸json格式的數(shù)據(jù)是很常見的場(chǎng)景。http+json實(shí)現(xiàn)數(shù)據(jù)傳輸?shù)姆绞骄哂幸子谩⒏咝У葍?yōu)點(diǎn),本篇文章將介紹如何通過c語(yǔ)言中的http+json實(shí)現(xiàn)數(shù)據(jù)傳輸。
#include#include #include #include #include #define POST_URL "http://example.com/api/post" #define GET_URL "http://example.com/api/get" //發(fā)送POST請(qǐng)求 void send_post_request() { CURL *curl = curl_easy_init(); if(curl) { //設(shè)置請(qǐng)求的URL地址 curl_easy_setopt(curl, CURLOPT_URL, POST_URL); //設(shè)置請(qǐng)求的Content-Type struct curl_slist *headers = NULL; headers = curl_slist_append(headers, "Content-Type: application/json"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); //設(shè)置請(qǐng)求數(shù)據(jù) json_object *jobj = json_object_new_object(); json_object *jstring = json_object_new_string("test"); json_object_object_add(jobj, "key1", jstring); char *post_data = json_object_to_json_string(jobj); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_data); //發(fā)起POST請(qǐng)求 CURLcode 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); json_object_put(jobj); } } //發(fā)送GET請(qǐng)求 void send_get_request() { CURL *curl = curl_easy_init(); if(curl) { //設(shè)置請(qǐng)求的URL地址 curl_easy_setopt(curl, CURLOPT_URL, GET_URL); //發(fā)起GET請(qǐng)求 CURLcode 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); } } int main() { send_post_request(); send_get_request(); return 0; }
以上代碼示例展示了常見的使用c語(yǔ)言中的curl庫(kù)和json-c庫(kù)發(fā)送http請(qǐng)求,并將json格式的數(shù)據(jù)傳輸?shù)椒?wù)器的方法。具體來說,使用curl的curl_easy_setopt函數(shù)設(shè)置請(qǐng)求的URL地址、請(qǐng)求方式、請(qǐng)求頭、請(qǐng)求數(shù)據(jù)等信息,通過json-c庫(kù)將數(shù)據(jù)轉(zhuǎn)換成json格式再發(fā)送請(qǐng)求。