多種語言腳本示例

#include <iostream>
#include <curl/curl.h>

// 回調函數,用於處理響應數據
int write_callback(char* data, size_t size, size_t nmemb, std::string* buffer) {
    int result = 0;
    if (buffer != nullptr) {
        buffer->append(data, size * nmemb);
        result = size * nmemb;
    }
    return result;
}

int main() {
    // 初始化 libcurl
    curl_global_init(CURL_GLOBAL_DEFAULT);

    // 設置請求 URL
    std::string url = "http://example.com/post";

    // 准備 JSON 數據
    std::string json = "{\"name\": \"John\", \"age\": 30}";

    // 發送 POST 請求
    CURL* curl = curl_easy_init();
    if (curl) {
        // 設置請求頭
        struct curl_slist* headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/json");

        // 設置請求選項
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json.c_str());
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);

        // 執行請求
        CURLcode res = curl_easy_perform(curl);
        if (res != CURLE_OK) {
            std::cout << "Failed to send POST request: " << curl_easy_strerror(res) << std::endl;
        }

        // 獲取響應結果
        long http_code = 0;
        curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);

        std::string response_data;
        curl_easy_getinfo(curl, CURLINFO_PRIVATE, &response_data);

        // 輸出請求的響應結果
        std::cout << "HTTP Status Code: " << http_code << std::endl;
        std::cout << "Response Data: " << response_data << std::endl;

        // 釋放資源
        curl_easy_cleanup(curl);
    }

    // 清理 libcurl
    curl_global_cleanup();

    return 0;
}