在使用C語言進(jìn)行接口服務(wù)開發(fā)時,需要進(jìn)行接口調(diào)用,而常用的接口通信格式是JSON,下面給出一個C語言調(diào)用接口服務(wù)JSON POST的例子。
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <curl/curl.h> int main(void) { CURL *curl; CURLcode res; curl_global_init(CURL_GLOBAL_ALL); curl = curl_easy_init(); if(curl) { char *url = "http://example.com/api"; char *data = "{\"name\":\"test\",\"age\":\"20\"}"; curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data); struct curl_slist *headers = NULL; headers = curl_slist_append(headers, "Content-Type: application/json"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); res = curl_easy_perform(curl); if(res != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); } curl_slist_free_all(headers); curl_easy_cleanup(curl); } curl_global_cleanup(); return 0; }
上述代碼使用CURL庫進(jìn)行接口調(diào)用,通過指定URL和JSON數(shù)據(jù),使用POST方式進(jìn)行請求。同時設(shè)置Content-Type為application/json格式,保證請求正常發(fā)送。