c http請(qǐng)求 json通常由以下幾個(gè)步驟完成:
1. 創(chuàng)建一個(gè)curl對(duì)象 CURL* curl = curl_easy_init(); 2. 設(shè)置url和HTTP請(qǐng)求方法 curl_easy_setopt(curl, CURLOPT_URL, "http://example.com/api/products"); curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET"); //HTTP請(qǐng)求方法為GET 3. 設(shè)置HTTP請(qǐng)求頭 struct curl_slist *headers = NULL; headers = curl_slist_append(headers, "Content-Type: application/json"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); 4. 發(fā)送請(qǐng)求并獲取返回結(jié)果 CURLcode res; string response; curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback); //設(shè)置寫回調(diào)函數(shù) curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); //將response作為回調(diào)函數(shù)參數(shù) res = curl_easy_perform(curl); //執(zhí)行curl_easy_perform函數(shù) if (res != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); } 5. 解析返回結(jié)果 json_t *root; json_error_t error; root = json_loads(response.c_str(), 0, &error); //解析json字符串 if (!root) { fprintf(stderr, "json error on line %d: %s\n", error.line, error.text); } //遍歷json對(duì)象 json_t *product; size_t index; json_array_foreach(root, index, product) { const char *name; json_t *price; json_unpack(product, "{s:s, s:o}", "name", &name, "price", &price); printf("%s: %s\n", name, json_string_value(price)); } 6. 釋放資源 json_decref(root); //釋放json對(duì)象 curl_easy_cleanup(curl); //釋放curl對(duì)象
以上就是c http請(qǐng)求 json的基本操作。通過(guò)這些方法,我們可以快速地獲取并解析服務(wù)器返回的json數(shù)據(jù),實(shí)現(xiàn)業(yè)務(wù)需求。