C JSON方式請求
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <curl/curl.h> #include <jansson.h> /** * @brief 通過Curl庫發送HTTP請求 * * @param url 請求的URL地址 * @param headers 請求頭部信息 * @param post_data POST請求數據 * @param resp_data 返回的結果數據 * @return int 0: 成功;其他: 失敗 */ int send_request(const char* url, const char* headers, const char* post_data, char** resp_data) { CURL* curl; CURLcode res; struct curl_slist* list = NULL; long resp_code = -1; char errbuf[CURL_ERROR_SIZE] = {0}; size_t resp_size = 0; curl = curl_easy_init(); if (curl) { list = curl_slist_append(list, headers); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list); curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_data); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, strlen(post_data)); /* 保存返回結果到內存中 */ curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_write_callback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &resp_data); /* 發送請求 */ res = curl_easy_perform(curl); /* 檢查HTTP返回代碼 */ curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &resp_code); if (res != CURLE_OK || resp_code != 200) { printf("HTTP request failed: %s\n", errbuf); return -1; } /* 清理工作 */ curl_slist_free_all(list); curl_easy_cleanup(curl); } else { printf("Curl init failed!\n"); return -1; } return 0; } /** * @brief 處理返回的JSON字符串并打印出來 * * @param str JSON字符串 */ void handle_json_str(char* str) { json_error_t error; json_t* root; json_t* data; root = json_loads(str, 0, &error); if (root) { printf("JSON Data: \n"); data = json_object_get(root, "data"); printf("title: %s\n", json_string_value(json_object_get(data, "title"))); printf("description: %s\n", json_string_value(json_object_get(data, "description"))); printf("url: %s\n", json_string_value(json_object_get(data, "url"))); json_decref(root); } else { printf("JSON decode failed: %s\n", error.text); } } int main(int argc, char const* argv[]) { char* resp_data = NULL; const char* url = "https://someapi.com/data"; const char* headers = "Content-Type: application/json"; const char* post_data = "{\"query\":\"java\",\"limit\":10}"; if (send_request(url, headers, post_data, &resp_data) == 0) { handle_json_str(resp_data); } return 0; }